Peer Connection
Confirm Endpoint
When confirming the Endpoint configured when you use the SDK, you can first read the section on PeerConn Access Domain Name in the Developer Guide to understand the Endpoint concept. Baidu Cloud has opened support in multiple regions, please refer to Region Selection Description.
Currently, the six regions are supported: "North China - Beijing", "South China- Guangzhou", "East China - Suzhou", "Hong Kong", "Finance Central China - Wuhan" and "North China - Baoding". The corresponding information is:
Access region | Corresponding Endpoint | Protocol |
---|---|---|
BJ | bcc.bj.baidubce.com | HTTP and HTTPS |
GZ | bcc.gz.baidubce.com | HTTP and HTTPS |
SU | bcc.su.baidubce.com | HTTP and HTTPS |
HKG | bcc.hkg.baidubce.com | HTTP and HTTPS |
FWH | bcc.fwh.baidubce.com | HTTP and HTTPS |
BD | bcc.bd.baidubce.com | HTTP and HTTPS |
Get the Key
To use Baidu AI Cloud PeerConn, you need to have a valid AK (Access Key ID) and SK (Secret Access Key) for signature authentication. AK/SK is assigned to users by the system and is a string to identify users and verify signatures for accessing PeerConn.
You can obtain and understand your AK/SK information through the following steps:
[Register Baidu Cloud Account](https://login.bce.baidu.com/reg.html? tpl=bceplat&from=portal)
[Create AK/SK](https://console.bce.baidu.com/iam/? _=1513940574695#/iam/accesslist)
Create a new PeerConn Client
PeerConn Client is the client of PeerConn service, which provides a series of methods for the developer to interact with PeerConn service.
Use AK/SK to Create a New PeerConn Client
Access PeerConn via AK/SK, and users can create a PeerConn Client by reference to the following codes:
import (
"github.com/baidubce/bce-sdk-go/services/vpc"
)
func main() {
// Access Key ID and Secret Access Key of users
ACCESS_KEY_ID, SECRET_ACCESS_KEY := <your-access-key-id>, <your-secret-access-key>
// User specified Endpoint
ENDPOINT := <domain-name>
// Initialize a PeerConnClient
peerConnClient, err := vpc.NewClient(AK, SK, ENDPOINT)
}
In the above code, ACCESS_KEY_ID
corresponds to the "Access Key ID" in the console, and SECRET_ACCESS_KEY
corresponds to the "Access Key Secret" in the console. For how to obtain it, please see How to Get AKSK in the Operation Guide . The third parameter “ENDPOINT” supports the domain name specified by the users themselves, and if it is set as a null string, default domain name is used as the service address of VPC.
Note: The
ENDPOINT
parameter needs to be defined by the domain name of the designated region. If the service region is Beijing, it isbcc.bj.baidubce.com
.
Create PeerConn Client with STS
Apply for STS token
PeerConn can implement temporary authorized access by a third party through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu Cloud. With STS, you can issue a third-party user with a custom time-based and privileged access credential. Third-party users can use the access credentials to directly call Baidu Cloud's API or SDK to access Baidu Cloud resources.
To access PeerConn through STS, users need to first apply for an authentication string through the STS client.
Create a new PeerConn Client with STS token
After STS is applied, STS Token can be configured in PeerConn Client to create PeerConn Client via STS Token.
Code example
GO SDK realizes the interface of STS service, and users can refer to the following complete code to apply for STS Token and create PeerConn Client object.
import (
"fmt"
"github.com/baidubce/bce-sdk-go/auth" // Import authentication module
"github.com/baidubce/bce-sdk-go/services/vpc" // Import VPC service module
"github.com/baidubce/bce-sdk-go/services/sts" // Import STS service module
)
func main() {
// Create the Client object of STS service, with Endpoint of default value
AK, SK := <your-access-key-id>, <your-secret-access-key>
stsClient, err := sts.NewClient(AK, SK)
if err != nil {
fmt.Println("create sts client object :", err)
return
}
// Obtain a temporary authentication token, with a valid period of 60 sec, and ACL null
stsObj, err := stsClient.GetSessionToken(60, "")
if err != nil {
fmt.Println("get session token failed:", err)
return
}
fmt.Println("GetSessionToken result:")
fmt.Println(" accessKeyId:", stsObj.AccessKeyId)
fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey)
fmt.Println(" sessionToken:", stsObj.SessionToken)
fmt.Println(" createTime:", stsObj.CreateTime)
fmt.Println(" expiration:", stsObj.Expiration)
fmt.Println(" userId:", stsObj.UserId)
// Create the Client object of PeerConn service with the temporary STS applied, with Endpoint of default value.
peerConnClient, err := peerConn.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com")
if err != nil {
fmt.Println("create PeerConn client failed:", err)
return
}
stsCredential, err := auth.NewSessionBceCredentials(
stsObj.AccessKeyId,
stsObj.SecretAccessKey,
stsObj.SessionToken)
if err != nil {
fmt.Println("create sts credential object failed:", err)
return
}
peerConnClient.Config.Credentials = stsCredential
}
Note: When using STS to configure PeerConn Client, no matter where the endpoint of the corresponding PeerConn service is, the endpoint of STS needs to be configured as http://sts.bj.baidubce.com. This default value is used to create STS object in the code above.
Configure HTTPS Protocol to Access PeerConn
PeerConn supports HTTPS, and you can use HTTPS to access PeerConn service in PeerConn GO SDK by indicating the mode of HTTPS in the Endpoint specified during creation of PeerConn Client object.
// import "github.com/baidubce/bce-sdk-go/services/vpc"
ENDPOINT := "https://bcc.bj.baidubce.com" // Indicate the use of HTTPS
AK, SK := <your-access-key-id>, <your-secret-access-key>
peerConnClient, _ := vpc.NewClient(AK, SK, ENDPOINT)
Configure PeerConn Client
To configure parameters of some details of PeerConn Client, you can use the export field Config
of PeerConn Client object for custom configuration after creating that object, and can configure agent, maximum connections, etc. for the client.
Use Agent
The following codes enable client to use agent to access PeerConn service:
// import "github.com/baidubce/bce-sdk-go/services/vpc"
// Create PeerConn Client object
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := peerConn.NewClient(AK, SK, ENDPOINT)
// The agent uses the local 8080 port
client.Config.ProxyUrl = "127.0.0.1:8080"
Set Network Parameters
Users can set the network parameters with the following sample code:
// import "github.com/baidubce/bce-sdk-go/services/vpc"
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := bcc.NewClient(AK, SK, ENDPOINT)
// Configuration is not retried, and the default is Back Off retry
client.Config.Retry = bce.NewNoRetryPolicy()
// Configure the connection time-out period as 30sec
client.Config.ConnectionTimeoutInMillis = 30 * 1000
Configure Generation of Signature String Option
// import "github.com/baidubce/bce-sdk-go/services/vpc"
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := bcc.NewClient(AK, SK, ENDPOINT)
// Configure the HTTPS request header for signature as `Host`
headersToSign := map[string]struct{}{"Host": struct{}{}}
client.Config.SignOption.HeadersToSign = HeadersToSign
// Configure the valid period of signature as 30sec
client.Config.SignOption.ExpireSeconds = 30
Parameter Description
When users use GO SDK to access PeerConn, the Config
field of PeerConn Client object created supports all parameters in the table below:
Name of configuration item | Type | Meaning |
---|---|---|
Endpoint | string | Domain name of request service |
ProxyUrl | string | Agent address of client request |
Region | string | Region of request resources |
UserAgent | string | User name, User-Agent header of HTTP request |
Credentials | *auth.BceCredentials | Authentication object of request is classified into ordinary AK/SK and STS |
SignOption | *auth.SignOptions | Signature option of authentication string |
Retry | RetryPolicy | Connection Retry Policy |
ConnectionTimeoutInMillis | int | Connection time-out period, in msec, and the default is 20min |
Note:
Credentials
field is created withauth.NewBceCredentials
andauth.NewSessionBceCredentials
functions, with the former as the default, and the latter used for STS authentication; for details, please see the subsection “Create PeerConn Client with STS”.SignOption
field is the option to generate signature string, for more information, please see the explanation in the table below:
Name | Type | Meaning |
---|---|---|
HeadersToSign | map[string]struct{} | HTTP header used to generate signature string |
Timestamp | int64 | The time stamp used to generate signature string is the value when the request is sent by default. |
ExpireSeconds | int | Valid period of signature string |
Among them, HeadersToSign defaults to `Host`, `Content-Type`, `Content-Length`, `Content-MD5`; TimeStamp is generally zero, indicating the timestamp when the authentication string is generated by the call, and the user should generally not clearly specify the value of this field; ExpireSeconds defaults to 1800 seconds or 30 minutes.
Retry
field specifies the retry policy, and support 2 retry policies currently:NoRetryPolicy
andBackOffRetryPolicy
. By default, the latter is used, and this retry policy specifies the maximum number of retry, longest time of retry and retry base. Retry is performed by multiplying the retry base by exponential growth of 2 until the maximum retry test or the maximum retry time is reached.
Peer Connection Management
The peer connection provides users with VPC-level network interconnection services, enabling users to implement traffic interconnection between different virtual networks, and realize stable and high-speed virtual network interconnection between the same region/cross region and the same user/different users.
Create Peer Connection
Use the following codes to create a peer connection.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.CreatePeerConnArgs{
// Set the bandwidth of the peer connection
BandwidthInMbps: 10,
// Set the description information of the peer connection
Description: "test peer conn",
// Set the local port name of the peer connection
LocalIfName: "local-interface",
// Set the id of the local vpc of the peer connection
LocalVpcId: vpcId,
// Set the peer account ID of the peer connection. This field is only required when establishing a cross-account peer connection
peerAccountId: peerAccountId,
// Set the id of the peer vpc of the peer connection
PeerVpcId: peerVpcId,
// Set the peer zone of the peer connection
PeerRegion: region,
// For the opposite terminal interface name of the peer connection, only the peer connection of the account allows to set the field.
PeerIfName: "peer-interface",
// Set the billing information for peer connections
Billing: &vpc.Billing{
PaymentTiming: vpc.PAYMENT_TIMING_POSTPAID,
},
}
result, err := client.CreatePeerConn(args)
if err != nil {
fmt.Println("create peerconn error: ", err)
return
}
fmt.Println("create peerconn success, peerconn id: ", result.PeerConnId)
Note:
- For the peer connections with the same local region and opposite terminal region, only the post-payment is supported.
- For the cross-account peer connection, the peer connection is available only after being accepted by the acceptor.
- For the peer connection of the same account, the system will trigger the opposite terminal for automatic acceptance.
- Only one peer connection exists between any two VPCs.
- The VPCs of the initiator and the acceptor cannot be the same.
- If the local vpc and opposite terminal vpc are both relay vpcs, the peer connection cannot be established.
Query Peer Connection List
Use the following codes to query the list of peer connections.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.ListPeerConnsArgs{
// Specify the vpc id to which the peer connection belongs
VpcId: vpcId,
// Specify the starting position of the query to obtain the list in batches
Marker: marker,
// Specify the maximum number per page, the maximum number does not exceed 1000. The default value is 1000.
MaxKeys: maxKeys,
}
result, err := client.ListPeerConn(args)
if err != nil {
fmt.Println("list peer conns error: ", err)
return
}
// Return the starting position of the mark query
fmt.Println("peerconn list marker: ", result.Marker)
// True means there are additional data in the following pages and false means the current page is the last page.
fmt.Println("peerconn list isTruncated: ", result.IsTruncated)
// The marker value requiring to be passed in order to acquire the next page. The domain doesn't appear when isTruncated is false.
fmt.Println("peerconn list nextMarker: ", result.NextMarker)
// Maximum number contained in each page.
fmt.Println("peerconn list maxKeys: ", result.MaxKeys)
// Get list information of peer connections
for _, pc := range result.PeerConns {
fmt.Println("peerconn id: ", pc.PeerConnId)
fmt.Println("peerconn role: ", pc.Role)
fmt.Println("peerconn status: ", pc.Status)
fmt.Println("peerconn bandwithInMbp: ", pc.BandwidthInMbps)
fmt.Println("peerconn description: ", pc.Description)
fmt.Println("peerconn localIfId: ", pc.LocalIfId)
fmt.Println("peerconn localIfName: ", pc.LocalIfName)
fmt.Println("peerconn localVpcId: ", pc.LocalVpcId)
fmt.Println("peerconn localRegion: ", pc.LocalRegion)
fmt.Println("peerconn peerVpcId: ", pc.PeerVpcId)
fmt.Println("peerconn peerRegion: ", pc.PeerRegion)
fmt.Println("peerconn peerAccountId: ", pc.PeerAccountId)
fmt.Println("peerconn paymentTiming: ", pc.PaymentTiming)
fmt.Println("peerconn dnsStatus: ", pc.DnsStatus)
fmt.Println("peerconn createdTime: ", pc.CreatedTime)
fmt.Println("peerconn expiredTime: ", pc.ExpiredTime)
}
This interface can be used to query and obtain all eligible peer connection information, where vpcId is an optional parameter.
View Peer Connection Details
Query the detailed information of a specific peer connection by the following code.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
result, err := client.GetPeerConnDetail(peerConnId, vpc.PEERCONN_ROLE_INITIATOR)
if err != nil {
fmt.Println("get peer conn detail error: ", err)
return
}
// Query to get the id of the peer connection
fmt.Println("peerconn id: ", result.PeerConnId)
// Query the role of the peer connection, "initiator" means the initiator and "acceptor" means the acceptor
fmt.Println("peerconn role: ", result.Role)
// Query to get the status of the peer connection
fmt.Println("peerconn status: ", result.Status)
// Query to get the bandwidth of the peer connection
fmt.Println("peerconn bandwithInMbp: ", result.BandwidthInMbps)
// Query to get the description of the peer connection
fmt.Println("peerconn description: ", result.Description)
// Query to get the local interface ID of the peer connection
fmt.Println("peerconn localIfId: ", result.LocalIfId)
// Query to get the local interface name of the peer connection
fmt.Println("peerconn localIfName: ", result.LocalIfName)
// Query to get the local VPC ID of the peer connection
fmt.Println("peerconn localVpcId: ", result.LocalVpcId)
// Query to get the local area of the peer connection
fmt.Println("peerconn localRegion: ", result.LocalRegion)
// Query to get the peer VPC ID of the peer connection
fmt.Println("peerconn peerVpcId: ", result.PeerVpcId)
// Query to get the peer area of the peer connection
fmt.Println("peerconn peerRegion: ", result.PeerRegion)
// Query to get the peer account ID of the peer connection
fmt.Println("peerconn peerAccountId: ", result.PeerAccountId)
// Query to get the charging method for peer connections
fmt.Println("peerconn paymentTiming: ", result.PaymentTiming)
// Query to get the dns status of the peer connection
fmt.Println("peerconn dnsStatus: ", result.DnsStatus)
// Query to get the creation time of the peer connection
fmt.Println("peerconn createdTime: ", result.CreatedTime)
// Query to get the expiration time of the peer connection
fmt.Println("peerconn expiredTime: ", result.ExpiredTime)
Note: The "initiator" refers to the initiator, and the "acceptor" refers to the acceptor. The details of the peer connections in the same region can be queried based on this. If this parameter is not set, either the initiator or the acceptor information is returned for the same region.
Update the Local Interface Name and Comments of Peer Connection
Use the following codes to update the local interface name and remarks of the peer connection.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.UpdatePeerConnArgs{
// Set the interface ID of the peer connection immutable, required
LocalIfId: localIfId,
// Set the local port name of the peer connection
LocalIfName: "test-update",
// Set the local port description of the peer connection
Description: "test-description",
}
if err := client.UpdatePeerConn(peerConnId, args); err != nil {
fmt.Println("update peer conn error: ", err)
return
}
fmt.Printf("update peer conn %s success", peerConnId)
Accept Peer Connection Request
Use the following codes to accept application information for peer connections.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
if err := client.AcceptPeerConnApply(peerConnId, clientToken); err != nil {
fmt.Println("accept peer conn error: ", err)
return
}
fmt.Printf("accept peer conn %s success.", peerConnId)
Note:
- When the connection request timeout initiated by the initiator is 7 days, the status of the peer connection of the initiator after time-out is "Consultation Failed".
- After the acceptor denies, the status of the peer connection of the initiator is "Consultation Failed".
Reject Peer Connection Request
Use the following codes to accept application information for peer connections.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
if err := client.RejectPeerConnApply(peerConnId, clientToken); err != nil {
fmt.Println("reject peer conn error: ", err)
return
}
fmt.Printf("reject peer conn %s success.", peerConnId)
Release Peer Connection
Use the following codes to release a specific peer connection.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
if err := client.DeletePeerConn(peerConnId, clientToken); err != nil {
fmt.Println("delete peer conn error: ", err)
return
}
fmt.Printf("delete peer conn %s success", peerConnId)
Note:
- The different accounts can be released by the initiator.
- The prepaid, available and unexpired peer connection cannot be released.
- The prepaid and consultation failed peer connection can be released.
Upgrade and Degrade of Peer Connection Bandwidth
Use the following codes to perform bandwidth upgrade operations for the specified peer connection.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.ResizePeerConnArgs{
// Specify the bandwidth of the peer connection
NewBandwidthInMbps: 20,
}
if err := client.ResizePeerConn(peerConnId, args); err != nil {
fmt.Println("resize peer conn error: ", err)
return
}
fmt.Printf("resize peer conn %s success.", peerConnId)
Note:
- The bandwidth can be upgraded and degraded only by the acceptor for different accounts.
- The prepaid peer connection can only upgrade and cannot degrade the bandwidth.
- The post-paid peer connection can both upgrade and degrade the bandwidth.
Peer Connection Renewal
Use the following codes to renew the peer connection and extend the expiration time.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.RenewPeerConnArgs{
// Specify the renewal information of the peer connection
Billing: &vpc.Billing{
Reservation: &vpc.Reservation{
ReservationLength: 1,
ReservationTimeUnit: "month",
},
},
}
if err := client.RenewPeerConn(peerConnId, args); err != nil {
fmt.Println("renew peer conn error: ", err)
return
}
fmt.Printf("renew peer conn %s success.", peerConnId)
Note:
- The postpaid peer connection cannot be renewed.
- The cross-account renewal can only be operated by the initiator.
Open the Synchronous DNS of Peer Connection
Use the following codes to enable peer connection to synchronize DNS records.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.PeerConnSyncDNSArgs{
// Specify the role of the peer connection, the initiator is "initiator" and the acceptor "acceptor"
Role: vpc.PEERCONN_ROLE_INITIATOR,
}
if err := client.OpenPeerConnSyncDNS(peerConnId, args); err != nil {
fmt.Println("open peer conn sync dns error: ", err)
return
}
fmt.Printf("open peer conn %s sync dns success.", peerConnId)
Note:
- The DNS can be enabled only when the status of peer connection is "available".
- The synchronization of DNS cannot be enabled when the DNS status of peer connection is "Synchronizing" or "Synchronization Closed".
Close the Synchronous DNS of Peer Connection
Use the following codes to close the peer connection to synchronize DNS records.
//import "github.com/baidubce/bce-sdk-go/services/vpc"
args := &vpc.PeerConnSyncDNSArgs{
// Specify the role of the peer connection, the initiator is "initiator" and the acceptor "acceptor"
Role: vpc.PEERCONN_ROLE_INITIATOR,
}
if err := client.ClosePeerConnSyncDNS(peerConnId, args); err != nil {
fmt.Println("close peer conn sync dns error: ", err)
return
}
fmt.Printf("close peer conn %s sync dns success.", peerConnId)
Note:
- The DNS can be closed only when the status of peer connection is "available".
- The synchronization of DNS cannot be closed when the DNS status of peer connection is "Synchronizing" or "Synchronization Closed".