本文整理汇总了Golang中github.com/juju/juju/api.DefaultDialOpts函数的典型用法代码示例。如果您正苦于以下问题:Golang DefaultDialOpts函数的具体用法?Golang DefaultDialOpts怎么用?Golang DefaultDialOpts使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultDialOpts函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Run
func (c *restoreCommand) Run(ctx *cmd.Context) error {
if c.showDescription {
fmt.Fprintf(ctx.Stdout, "%s\n", c.Info().Purpose)
return nil
}
if err := c.Log.Start(ctx); err != nil {
return err
}
agentConf, err := extractConfig(c.backupFile)
if err != nil {
return errors.Annotate(err, "cannot extract configuration from backup file")
}
progress("extracted credentials from backup file")
store, err := configstore.Default()
if err != nil {
return err
}
cfg, err := c.Config(store)
if err != nil {
return err
}
env, err := rebootstrap(cfg, ctx, c.Constraints)
if err != nil {
return errors.Annotate(err, "cannot re-bootstrap environment")
}
progress("connecting to newly bootstrapped instance")
var apiState *api.State
// The state server backend may not be ready to accept logins so we retry.
// We'll do up to 8 retries over 2 minutes to give the server time to come up.
// Typically we expect only 1 retry will be needed.
attempt := utils.AttemptStrategy{Delay: 15 * time.Second, Min: 8}
for a := attempt.Start(); a.Next(); {
apiState, err = juju.NewAPIState(env, api.DefaultDialOpts())
if err == nil || errors.Cause(err).Error() != "EOF" {
break
}
progress("bootstrapped instance not ready - attempting to redial")
}
if err != nil {
return errors.Annotate(err, "cannot connect to bootstrap instance")
}
progress("restoring bootstrap machine")
machine0Addr, err := restoreBootstrapMachine(apiState, c.backupFile, agentConf)
if err != nil {
return errors.Annotate(err, "cannot restore bootstrap machine")
}
progress("restored bootstrap machine")
apiState, err = juju.NewAPIState(env, api.DefaultDialOpts())
progress("opening state")
if err != nil {
return errors.Annotate(err, "cannot connect to api server")
}
progress("updating all machines")
if err := updateAllMachines(apiState, machine0Addr); err != nil {
return errors.Annotate(err, "cannot update machines")
}
return nil
}
示例2: newAPIConnectionFromNames
func newAPIConnectionFromNames(
c *gc.C,
controller, account, model string,
store jujuclient.ClientStore,
apiOpen api.OpenFunc,
getBootstrapConfig func(string) (*config.Config, error),
) (api.Connection, error) {
params := juju.NewAPIConnectionParams{
Store: store,
ControllerName: controller,
BootstrapConfig: getBootstrapConfig,
DialOpts: api.DefaultDialOpts(),
}
if account != "" {
accountDetails, err := store.AccountByName(controller, account)
c.Assert(err, jc.ErrorIsNil)
params.AccountDetails = accountDetails
}
if model != "" {
modelDetails, err := store.ModelByName(controller, account, model)
c.Assert(err, jc.ErrorIsNil)
params.ModelUUID = modelDetails.ModelUUID
}
return juju.NewAPIFromStore(params, apiOpen)
}
示例3: apiInfoConnect
// apiInfoConnect looks for endpoint on the given environment and
// tries to connect to it, sending the result on the returned channel.
func apiInfoConnect(store configstore.Storage, info configstore.EnvironInfo, apiOpen apiOpenFunc, stop <-chan struct{}) (apiState, error) {
endpoint := info.APIEndpoint()
if info == nil || len(endpoint.Addresses) == 0 {
return nil, &infoConnectError{fmt.Errorf("no cached addresses")}
}
logger.Infof("connecting to API addresses: %v", endpoint.Addresses)
var environTag names.Tag
if endpoint.EnvironUUID != "" {
// Note: we should be validating that EnvironUUID contains a
// valid UUID.
environTag = names.NewEnvironTag(endpoint.EnvironUUID)
}
username := info.APICredentials().User
if username == "" {
username = "admin"
}
apiInfo := &api.Info{
Addrs: endpoint.Addresses,
CACert: endpoint.CACert,
Tag: names.NewUserTag(username),
Password: info.APICredentials().Password,
EnvironTag: environTag,
}
st, err := apiOpen(apiInfo, api.DefaultDialOpts())
if err != nil {
return nil, &infoConnectError{err}
}
return st, nil
}
示例4: hostedAPI
func (s *undertakerSuite) hostedAPI(c *gc.C) (*undertaker.Client, *state.State) {
otherState := s.Factory.MakeModel(c, &factory.ModelParams{Name: "hosted_env"})
password, err := utils.RandomPassword()
c.Assert(err, jc.ErrorIsNil)
machine := s.Factory.MakeMachine(c, &factory.MachineParams{
Jobs: []state.MachineJob{state.JobManageModel},
Password: password,
Nonce: "fake_nonce",
})
// Connect to hosted environ from controller.
info := s.APIInfo(c)
info.Tag = machine.Tag()
info.Password = password
info.Nonce = "fake_nonce"
info.ModelTag = otherState.ModelTag()
otherAPIState, err := api.Open(info, api.DefaultDialOpts())
c.Assert(err, jc.ErrorIsNil)
undertakerClient := undertaker.NewClient(otherAPIState)
c.Assert(undertakerClient, gc.NotNil)
return undertakerClient, otherState
}
示例5: dialLogsinkAPI
func dialLogsinkAPI(apiInfo *api.Info) (*websocket.Conn, error) {
// TODO(mjs) Most of this should be extracted to be shared for
// connections to both /log (debuglog) and /logsink.
header := utils.BasicAuthHeader(apiInfo.Tag.String(), apiInfo.Password)
header.Set("X-Juju-Nonce", apiInfo.Nonce)
conn, err := api.Connect(apiInfo, "/logsink", header, api.DefaultDialOpts())
if err != nil {
return nil, errors.Annotate(err, "failed to connect to logsink API")
}
// Read the initial error and translate to a real error.
// Read up to the first new line character. We can't use bufio here as it
// reads too much from the reader.
line := make([]byte, 4096)
n, err := conn.Read(line)
if err != nil {
return nil, errors.Annotate(err, "unable to read initial response")
}
line = line[0:n]
var errResult params.ErrorResult
err = json.Unmarshal(line, &errResult)
if err != nil {
return nil, errors.Annotate(err, "unable to unmarshal initial response")
}
if errResult.Error != nil {
return nil, errors.Annotatef(err, "initial server error")
}
return conn, nil
}
示例6: apiInfoConnect
// apiInfoConnect looks for endpoint on the given environment and
// tries to connect to it, sending the result on the returned channel.
func apiInfoConnect(info configstore.EnvironInfo, apiOpen api.OpenFunc, stop <-chan struct{}, bClient *httpbakery.Client) (api.Connection, error) {
endpoint := info.APIEndpoint()
if info == nil || len(endpoint.Addresses) == 0 {
return nil, &infoConnectError{fmt.Errorf("no cached addresses")}
}
logger.Infof("connecting to API addresses: %v", endpoint.Addresses)
var modelTag names.ModelTag
if names.IsValidModel(endpoint.ModelUUID) {
modelTag = names.NewModelTag(endpoint.ModelUUID)
}
apiInfo := &api.Info{
Addrs: endpoint.Addresses,
CACert: endpoint.CACert,
Tag: environInfoUserTag(info),
Password: info.APICredentials().Password,
ModelTag: modelTag,
}
if apiInfo.Tag == nil {
apiInfo.UseMacaroons = true
}
dialOpts := api.DefaultDialOpts()
dialOpts.BakeryClient = bClient
st, err := apiOpen(apiInfo, dialOpts)
if err != nil {
return nil, &infoConnectError{err}
}
return st, nil
}
示例7: TestMigration
func (s *Suite) TestMigration(c *gc.C) {
masterClient := newStubMasterClient(s.stub)
w := migrationmaster.New(masterClient)
// Trigger migration.
masterClient.watcher.changes <- migration.TargetInfo{
ControllerTag: names.NewModelTag("uuid"),
Addrs: []string{"1.2.3.4:5"},
CACert: "cert",
AuthTag: names.NewUserTag("admin"),
Password: "secret",
}
// This error is temporary while migrationmaster is a WIP.
runWorkerAndWait(c, w, "migration seen and aborted")
// Observe that the migration was seen, the model exported, an API
// connection to the target controller was made, the model was
// imported and then the migration aborted.
s.stub.CheckCalls(c, []jujutesting.StubCall{
{"masterClient.Watch", nil},
{"masterClient.Export", nil},
{"apiOpen", []interface{}{&api.Info{
Addrs: []string{"1.2.3.4:5"},
CACert: "cert",
Tag: names.NewUserTag("admin"),
Password: "secret",
}, api.DefaultDialOpts()}},
{"APICall:MigrationTarget.Import",
[]interface{}{params.SerializedModel{Bytes: fakeSerializedModel}}},
{"masterClient.SetPhase", []interface{}{migration.ABORT}},
{"Connection.Close", nil},
})
}
示例8: apiInfoConnect
// apiInfoConnect looks for endpoint on the given environment and
// tries to connect to it, sending the result on the returned channel.
func apiInfoConnect(store configstore.Storage, info configstore.EnvironInfo, apiOpen apiOpenFunc, stop <-chan struct{}) (apiState, error) {
endpoint := info.APIEndpoint()
if info == nil || len(endpoint.Addresses) == 0 {
return nil, &infoConnectError{fmt.Errorf("no cached addresses")}
}
logger.Infof("connecting to API addresses: %v", endpoint.Addresses)
var environTag names.EnvironTag
if names.IsValidEnvironment(endpoint.EnvironUUID) {
environTag = names.NewEnvironTag(endpoint.EnvironUUID)
} else {
// For backwards-compatibility, we have to allow connections
// with an empty UUID. Login will work for the same reasons.
logger.Warningf("ignoring invalid API endpoint environment UUID %v", endpoint.EnvironUUID)
}
apiInfo := &api.Info{
Addrs: endpoint.Addresses,
CACert: endpoint.CACert,
Tag: environInfoUserTag(info),
Password: info.APICredentials().Password,
EnvironTag: environTag,
}
st, err := apiOpen(apiInfo, api.DefaultDialOpts())
if err != nil {
return nil, &infoConnectError{err}
}
return st, nil
}
示例9: testAddModel
func (s *cmdControllerSuite) testAddModel(c *gc.C, args ...string) {
// The JujuConnSuite doesn't set up an ssh key in the fake home dir,
// so fake one on the command line. The dummy provider also expects
// a config value for 'controller'.
args = append([]string{"add-model", "new-model"}, args...)
args = append(args,
"--config", "authorized-keys=fake-key",
"--config", "controller=false",
)
context := s.run(c, args...)
c.Check(testing.Stdout(context), gc.Equals, "")
c.Check(testing.Stderr(context), gc.Equals, `
Added 'new-model' model on dummy/dummy-region with credential 'cred' for user 'admin'
`[1:])
// Make sure that the saved server details are sufficient to connect
// to the api server.
accountDetails, err := s.ControllerStore.AccountDetails("kontroll")
c.Assert(err, jc.ErrorIsNil)
modelDetails, err := s.ControllerStore.ModelByName("kontroll", "[email protected]/new-model")
c.Assert(err, jc.ErrorIsNil)
api, err := juju.NewAPIConnection(juju.NewAPIConnectionParams{
Store: s.ControllerStore,
ControllerName: "kontroll",
AccountDetails: accountDetails,
ModelUUID: modelDetails.ModelUUID,
DialOpts: api.DefaultDialOpts(),
OpenAPI: api.Open,
})
c.Assert(err, jc.ErrorIsNil)
api.Close()
}
示例10: TestUploadToolsOtherEnvironment
func (s *apiEnvironmentSuite) TestUploadToolsOtherEnvironment(c *gc.C) {
// setup other environment
otherState := s.Factory.MakeModel(c, nil)
defer otherState.Close()
info := s.APIInfo(c)
info.ModelTag = otherState.ModelTag()
otherAPIState, err := api.Open(info, api.DefaultDialOpts())
c.Assert(err, jc.ErrorIsNil)
defer otherAPIState.Close()
otherClient := otherAPIState.Client()
defer otherClient.ClientFacade.Close()
newVersion := version.MustParseBinary("5.4.3-quantal-amd64")
vers := newVersion.String()
// build fake tools
tgz, checksum := coretesting.TarGz(
coretesting.NewTarFile(jujunames.Jujud, 0777, "jujud contents "+vers))
toolsList, err := otherClient.UploadTools(bytes.NewReader(tgz), newVersion)
c.Assert(err, jc.ErrorIsNil)
c.Assert(toolsList, gc.HasLen, 1)
c.Assert(toolsList[0].SHA256, gc.Equals, checksum)
toolStrg, err := otherState.ToolsStorage()
defer toolStrg.Close()
c.Assert(err, jc.ErrorIsNil)
meta, closer, err := toolStrg.Open(vers)
defer closer.Close()
c.Assert(err, jc.ErrorIsNil)
c.Assert(meta.SHA256, gc.Equals, checksum)
c.Assert(meta.Version, gc.Equals, vers)
}
示例11: secretKeyLogin
func (c *registerCommand) secretKeyLogin(addrs []string, request params.SecretKeyLoginRequest) (*params.SecretKeyLoginResponse, error) {
buf, err := json.Marshal(&request)
if err != nil {
return nil, errors.Annotate(err, "marshalling request")
}
r := bytes.NewReader(buf)
// Determine which address to use by attempting to open an API
// connection with each of the addresses. Note that we do not
// know the CA certificate yet, so we do not want to send any
// sensitive information. We make no attempt to log in until
// we can verify the server's identity.
opts := api.DefaultDialOpts()
opts.InsecureSkipVerify = true
conn, err := c.apiOpen(&api.Info{
Addrs: addrs,
SkipLogin: true,
// NOTE(axw) CACert is required, but ignored if
// InsecureSkipVerify is set. We should try to
// bring together CACert and InsecureSkipVerify
// so they can be validated together.
CACert: "ignored",
}, opts)
if err != nil {
return nil, errors.Trace(err)
}
apiAddr := conn.Addr()
if err := conn.Close(); err != nil {
return nil, errors.Trace(err)
}
// Using the address we connected to above, perform the request.
urlString := fmt.Sprintf("https://%s/register", apiAddr)
httpReq, err := http.NewRequest("POST", urlString, r)
if err != nil {
return nil, errors.Trace(err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpClient := utils.GetNonValidatingHTTPClient()
httpResp, err := httpClient.Do(httpReq)
if err != nil {
return nil, errors.Trace(err)
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
var resp params.ErrorResult
if err := json.NewDecoder(httpResp.Body).Decode(&resp); err != nil {
return nil, errors.Trace(err)
}
return nil, resp.Error
}
var resp params.SecretKeyLoginResponse
if err := json.NewDecoder(httpResp.Body).Decode(&resp); err != nil {
return nil, errors.Trace(err)
}
return &resp, nil
}
示例12: otherEnviron
func (s *clientSuite) otherEnviron(c *gc.C) (*state.State, *api.State) {
otherSt := s.Factory.MakeEnvironment(c, nil)
info := s.APIInfo(c)
info.EnvironTag = otherSt.EnvironTag()
apiState, err := api.Open(info, api.DefaultDialOpts())
c.Assert(err, jc.ErrorIsNil)
return otherSt, apiState
}
示例13: otherModel
func (s *clientSuite) otherModel(c *gc.C) (*state.State, api.Connection) {
otherSt := s.Factory.MakeModel(c, nil)
info := s.APIInfo(c)
info.ModelTag = otherSt.ModelTag()
apiState, err := api.Open(info, api.DefaultDialOpts())
c.Assert(err, jc.ErrorIsNil)
return otherSt, apiState
}
示例14: TestClientNoNeedToPing
func (s *pingerSuite) TestClientNoNeedToPing(c *gc.C) {
s.PatchValue(apiserver.MaxClientPingInterval, time.Duration(0))
st, err := api.Open(s.APIInfo(c), api.DefaultDialOpts())
c.Assert(err, jc.ErrorIsNil)
defer st.Close()
time.Sleep(coretesting.ShortWait)
err = st.Ping()
c.Assert(err, jc.ErrorIsNil)
}
示例15: openAPIConn
func openAPIConn(targetInfo *migration.TargetInfo) (api.Connection, error) {
apiInfo := &api.Info{
Addrs: targetInfo.Addrs,
CACert: targetInfo.CACert,
Tag: targetInfo.AuthTag,
Password: targetInfo.Password,
}
return apiOpen(apiInfo, api.DefaultDialOpts())
}