Esempio n. 1
0
func (c *Client) Stop(id string, remote *kite.Client) error {
	stopArgs := &args{
		MachineId: id,
		Provider:  c.Provider,
	}

	resp, err := remote.Tell("stop", stopArgs)
	if err != nil {
		return err
	}

	var result kloud.ControlResult
	err = resp.Unmarshal(&result)
	if err != nil {
		return err
	}

	eArgs := kloud.EventArgs([]kloud.EventArg{
		{
			EventId: stopArgs.MachineId,
			Type:    "stop",
		},
	})

	return listenEvent(eArgs, machinestate.Stopped, remote)
}
Esempio n. 2
0
func (c *Client) CreateSnapshot(id string, remote *kite.Client) error {
	createSnapshotArgs := &args{
		MachineId: id,
		Provider:  c.Provider,
	}

	resp, err := remote.Tell("createSnapshot", createSnapshotArgs)
	if err != nil {
		return err
	}

	var result kloud.ControlResult
	err = resp.Unmarshal(&result)
	if err != nil {
		return err
	}

	eArgs := kloud.EventArgs([]kloud.EventArg{
		{
			EventId: createSnapshotArgs.MachineId,
			Type:    "createSnapshot",
		},
	})

	return listenEvent(eArgs, machinestate.Running, remote)
}
Esempio n. 3
0
func (s *Stack) checkTunnel(c *kite.Client) error {
	resp, err := c.TellWithTimeout("tunnel.info", 2*time.Minute)
	if err != nil {
		return err
	}

	var info tunnel.InfoResponse
	if err := resp.Unmarshal(&info); err != nil {
		return err
	}

	s.Log.Debug("received tunnel.info response: %+v", &info)

	if info.State != tunnel.StateConnected {
		// We do not fail here, as the tunnel can be recovering
		// and we might hit the window when it's not yet done.
		// However we log, to show kloud observed problems with
		// connection.
		s.Log.Warning("%s: want tunnel to be %q, was %q instead", c.ID, tunnel.StateConnected, info.State)

		return nil
	}

	if _, ok := info.Ports["kite"]; !ok {
		// Every klient has its connection to kontrol tunneled, thus
		// tunnel.info should report ports for kite. Warn if there're
		// none to show kloud observed unexpected behavior.
		// However it is not critical though, as we were able to
		// kite.ping the klient, it means the klient may have some
		// other problems (connection with host kite etc.).
		s.Log.Warning("%s: no ports for kite", c.ID)
	}

	return nil
}
Esempio n. 4
0
func TodosHandler(app *kite.Client, w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")

	result, err := app.Tell("todos", token)
	if err != nil {
		fmt.Println("Failed to get todos", err)
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	w.Write(result.Raw)
}
Esempio n. 5
0
// configureKiteClient
func configureKiteClient(c *kite.Client) error {
	// Set reconnect.
	// https://github.com/koding/kite/blob/master/client.go#L300
	c.Reconnect = true

	return nil
}
Esempio n. 6
0
// watch watches the events of the specified event type.
func watch(k *kite.Client, eventType string, eventId string, interval time.Duration) error {
	eventArgs := stack.EventArgs([]stack.EventArg{
		{
			Type:    eventType,
			EventId: eventId,
		},
	})

	for {
		resp, err := k.TellWithTimeout("event", defaultTellTimeout, eventArgs)
		if err != nil {
			return err
		}

		var events []stack.EventResponse
		if err := resp.Unmarshal(&events); err != nil {
			return err
		}

		if len(events) == 0 {
			return errors.New("incoming event response is not an array")
		}

		if events[0].Error != nil {
			return events[0].Error
		}

		DefaultUi.Info(fmt.Sprintf("%s ==> %s [Status: %s Percentage: %d]",
			fmt.Sprint(time.Now())[:19],
			events[0].Event.Message,
			events[0].Event.Status,
			events[0].Event.Percentage,
		))

		if events[0].Event.Error != "" {
			err := errors.New(events[0].Event.Error)
			DefaultUi.Error(err.Error())
			return err
		}

		if events[0].Event.Percentage == 100 {
			return nil
		}

		time.Sleep(interval)
	}
}
Esempio n. 7
0
File: cmd.go Progetto: koding/koding
func (c *Cmd) SingleMachine(id string, k *kite.Client) (string, error) {
	resp, err := k.Tell(c.command, &KloudArgs{
		MachineId: id,
		Provider:  *c.provider,
	})
	if err != nil {
		return "", err
	}

	var result stack.ControlResult
	err = resp.Unmarshal(&result)
	if err != nil {
		return "", err
	}

	return result.EventId, nil
}
Esempio n. 8
0
func (i *Info) SingleMachine(id string, k *kite.Client) (string, error) {
	infoArgs := &KloudArgs{
		MachineId: id,
		Provider:  *i.provider,
	}

	resp, err := k.Tell("info", infoArgs)
	if err != nil {
		return "", err
	}

	var result stack.InfoResponse
	err = resp.Unmarshal(&result)
	if err != nil {
		return "", err
	}

	return result.State.String(), nil
}
Esempio n. 9
0
func LoginHandler(auth *kite.Client, w http.ResponseWriter, r *http.Request) {
	params := map[string]string{
		"user": r.FormValue("username"),
		"pass": r.FormValue("password"),
	}

	result, err := auth.Tell("login", params)
	if err != nil {
		fmt.Println("Failed to login:"******"token": token})

	w.Write(json)
}
Esempio n. 10
0
func unmount(kite *kite.Client, name, path string, log logging.Logger) error {
	req := req.UnmountFolder{
		Name:      name,
		LocalPath: path,
	}

	// currently there's no return response to care about
	_, err := kite.Tell("remote.unmountFolder", req)
	return err
}
Esempio n. 11
0
func getListOfMachines(kite *kite.Client) (list.KiteInfos, error) {
	res, err := kite.Tell("remote.list")
	if err != nil {
		return nil, err
	}

	var infos []list.KiteInfo
	if err := res.Unmarshal(&infos); err != nil {
		return nil, err
	}

	return infos, nil
}
Esempio n. 12
0
func (c *Client) Build(id string, remote *kite.Client) error {
	buildArgs := &args{
		MachineId: id,
		Provider:  c.Provider,
		TerraformContext: fmt.Sprintf(`
provider "aws" {
    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    region = "%s"
}

resource "aws_instance" "example" {
    ami = "ami-d05e75b8"
    instance_type = "%s"
}`, c.region(), c.instanceType()),
	}

	resp, err := remote.Tell("build", buildArgs)
	if err != nil {
		return err
	}

	var result kloud.ControlResult
	err = resp.Unmarshal(&result)
	if err != nil {
		return err
	}

	eArgs := kloud.EventArgs([]kloud.EventArg{
		{
			EventId: buildArgs.MachineId,
			Type:    "build",
		},
	})

	return listenEvent(eArgs, machinestate.Running, remote)

}
Esempio n. 13
0
// listenEvent calls the event method of kloud with the given arguments until
// the desiredState is received. It times out if the desired state is not
// reached in 10 miunuts.
func listenEvent(args kloud.EventArgs, desiredState machinestate.State, remote *kite.Client) error {
	tryUntil := time.Now().Add(time.Minute * 10)
	for {
		resp, err := remote.Tell("event", args)
		if err != nil {
			return err
		}

		var events []kloud.EventResponse
		if err := resp.Unmarshal(&events); err != nil {
			return err
		}

		e := events[0]
		if e.Error != nil {
			return e.Error
		}

		// fmt.Printf("e = %+v\n", e)

		event := e.Event
		if event.Error != "" {
			return fmt.Errorf("%s: %s", args[0].Type, event.Error)
		}

		if event.Status == desiredState {
			return nil
		}

		if time.Now().After(tryUntil) {
			return fmt.Errorf("Timeout while waiting for state %s", desiredState)
		}

		time.Sleep(2 * time.Second)
		continue // still pending
	}
}
Esempio n. 14
0
func TodosHandler(auth *kite.Client, db *kite.Client, r *kite.Request) (interface{}, error) {
	token, err := r.Args.One().String()
	if err != nil {
		return nil, BadToken
	}

	result, _ := auth.Tell("validateToken", token)
	if !result.MustBool() {
		return nil, BadToken
	}

	result, _ = db.Tell("query", "todos")

	var (
		arr, _ = result.Slice()
		todos  []string
	)
	for _, a := range arr {
		val, _ := a.String()
		todos = append(todos, val)
	}

	return todos, nil
}
Esempio n. 15
0
func main() {
	authorizer := auth.NewAuthorizer()

	authConfig, err := conf.NewConfig("auth")
	if err != nil {
		fmt.Println("Error getting config", err)
		return
	}

	k := kitewrapper.NewKiteWrapper(authConfig)
	err = k.RegisterToKontrol()
	if err != nil {
		fmt.Println("Failed to register", err)
		return
	}

	var dbKite *kite.Client

	go func() {
		var err error

		dbKite, err = k.FindAndDial("db_accessor")
		if err != nil {
			fmt.Println("Failed to dial db service", err)
			// return
		}
	}()

	// Add our handler method
	k.HandleFunc("login", func(r *kite.Request) (interface{}, error) {
		var (
			params, _ = r.Args.One().Map()
			user, _   = params["user"].String()
			pass, _   = params["pass"].String()
		)

		if user == User && pass == Pass {
			return authorizer.Token, nil
		}

		return nil, BadCredentials
	})

	k.HandleFunc("profile", func(r *kite.Request) (interface{}, error) {
		token, err := r.Args.One().String()
		if err != nil {
			return nil, BadCredentials
		}

		if !authorizer.Validate(token) {
			return nil, BadCredentials
		}

		result, err := dbKite.Tell("query", "profile")
		if err != nil {
			return nil, err
		}

		var (
			profileMap, _ = result.Map()
			profile       = make(map[string]string)
		)
		for name, value := range profileMap {
			val, _ := value.String()
			profile[name] = val
		}

		return profile, nil
	})

	k.HandleFunc("validateToken", func(r *kite.Request) (interface{}, error) {
		token, err := r.Args.One().String()

		if err != nil {
			return false, BadCredentials
		}

		return authorizer.Validate(token), nil
	})

	k.Run()
}