Vpn
VPN Service
Overview
This document mainly introduces the use of VPN GO SDK. Before using this document, you need to know some basic knowledge of VPN and have already subscribed VPN services. If you want to know more about VPN, refer to Product Description and Operation Guide.
Initialization
Confirm Endpoint
When confirming the Endpoint configured when you use the SDK, you can first read the section on VPN Access Domain Name in the Developer Guide to understand the Endpoint concept. Baidu AI Cloud currently supports multi-regions. Please see Region Selection Instructions.
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 VPN, 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 VPN.
You can obtain and understand your AK/SK information through the following steps:
Register Baidu AI Cloud Account
Create a VPN Client
VPN Client is the client of VPN service, which provides a series of methods for the developer to interact with VPN service.
Create a VPN Client with AK/SK
Access VPN via AK/SK, and users can create a VPN Client by reference to the following codes:
import (
"github.com/baidubce/bce-sdk-go/services/vpn"
)
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 VPNClient
vpnClient, err := vpn.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:
ENDPOINT
needs to be defined with the domain name of specified region. For example, if the service region is Beijing, the domain name isbcc.bj.baidubce.com
.
Create VPN Client with STS
Apply for STS token
VPN 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. The third-party user can use the access credential to directly call API or SDK of Baidu AI Cloud to access its resources.
To access to VPN via STS, you need to apply for an authentication string via client of STS, for the application method.
Create a VPN Client with STS token
After STS is applied, STS Token can be configured in VPN Client to create VPN 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 VPN Client object.
import (
"fmt"
"github.com/baidubce/bce-sdk-go/auth" // Import authentication module
"github.com/baidubce/bce-sdk-go/services/vpn" // Import VPN 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 VPN service with the temporary STS applied, with Endpoint of default value.
vpnClient, err := vpn.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com")
if err != nil {
fmt.Println("create vpn 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
}
vpnClient.Config.Credentials = stsCredential
}
Note: Currently, when STS is used to configure VPN Client, wherever the Endpoint corresponding to VPN 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 to Access VPN
VPN supports HTTPS, and you can use HTTPS to access VPN service in VPN GO SDK by indicating the mode of HTTPS in the Endpoint specified during creation of VPN Client object.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
ENDPOINT := "https://bcc.bj.baidubce.com" // Indicate the use of HTTPS
AK, SK := <your-access-key-id>, <your-secret-access-key>
vpnClient, _ := vpn.NewClient(AK, SK, ENDPOINT)
Configure VPN Client
To configure parameters of some details of VPN Client, you can use the export field Config
of VPN 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 VPN service:
// import "github.com/baidubce/bce-sdk-go/services/vpn"
// Create VPN Client object
AK, SK := <your-access-key-id>, <your-secret-access-key>
ENDPOINT := "bcc.bj.baidubce.com"
client, _ := vpn.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/vpn"
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/vpn"
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 VPN, the Config
field of VPN 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 |
Description:
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 VPN 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 |
Where the default values of HeadersToSign are `Host`, `Content-Type`, `Content-Length` and `Content- MD5`; TimeStamp is generally zero, indicating the time stamp when call is used to generate string, and generally the value of that field should not be specified expressly; the default value of ExpireSeconds is 1,800sec, i.e. 30min.
Retry
field specifies the retry strategy, and support 2 retry strategies currently:NoRetryPolicy
andBackOffRetryPolicy
. By default, the latter is used, and this retry strategy 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.
Create VPN
Use the following code to apply for a VPN.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.CreateVpnGatewayArgs{
VpnName: "TestSDK-VPN",
Description: "vpn test",
VpcId: "vpcId",
Billing: &Billing{
PaymentTiming: PAYMENT_TIMING_PREPAID,
Reservation: &Reservation{
ReservationLength: 1,
ReservationTimeUnit: "month",
},
},
ClientToken: getClientToken(),
}
result, err := client.CreateVpnGateway(args)
if err != nil {
fmt.Printf("create vpn error: %+v\n", err)
return
}
fmt.Println("create vpn success, vpn: ", result.VpnId)
Query VPN list
You can query the VPN list using the following code:
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.ListVpnGatewayArgs{
MaxKeys: 1000,
VpcId: "vpcId",
}
result, err := client.ListVpnGateway(args)
if err != nil {
fmt.Printf("list vpn error: %+v\n", err)
return
}
// Return to the starting position of the mark query
fmt.Println("vpn 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("vpn 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("vpn list nextMarker: ", result.NextMarker)
// Maximum number contained in each page.
fmt.Println("vpn list maxKeys: ", result.MaxKeys)
// Get the list information of vpn
for _, e := range res.Vpns {
fmt.Println("vpn id: ", e.VpnId)
fmt.Println("vpn eip: ", e.Eip)
fmt.Println("vpn status: ", e.Status)
fmt.Println("vpn vpcId: ", e.VpcId)
fmt.Println("vpn description: ", e.Description)
fmt.Println("vpn expiredTime: ", e.ExpiredTime)
fmt.Println("vpn paymentTiming: ", e.ProductType)
fmt.Println("vpn vpnConnNum: ", e.VpnConnNum)
fmt.Println("vpn bandwidthInMbps: ", e.BandwidthInMbps)
fmt.Println("vpn vpnName: ", e.Name)
fmt.Println("vpn expireTime: ", e.ExpiredTime)
}
Query VPN details
Use the following code to query the details of VPN.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
result,err:=vpn.GetVpnGatewayDetail("vpnId")
if err != nil {
fmt.Printf("get vpn detail error: %+v\n", err)
return
}
fmt.Println("vpn id: ", result.VpnId)
fmt.Println("vpn eip: ", result.Eip)
fmt.Println("vpn status: ", result.Status)
fmt.Println("vpn vpcId: ", result.VpcId)
fmt.Println("vpn description: ", result.Description)
fmt.Println("vpn expiredTime: ", result.ExpiredTime)
fmt.Println("vpn paymentTiming: ", result.ProductType)
fmt.Println("vpn vpnConnNum: ", result.VpnConnNum)
fmt.Println("vpn bandwidthInMbps: ", result.BandwidthInMbps)
fmt.Println("vpn vpnName: ", result.Name)
fmt.Println("vpn expireTime: ", result.ExpiredTime)
}
Update VPN gateway
Use the following code to update the VPN gateway.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.UpdateVpnGatewayArgs{
ClientToken: getClientToken(),
Name: "vpnTest",
}
err := client.UpdateVpnGateway("vpnId", args)
if err != nil {
fmt.Printf("update vpn error: %+v\n", err)
return
}
fmt.Printf("update vpn success\n")
Release VPN
Use the following code to release the specified VPN.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
err = client.DeleteVpn(vpnId, clientToken)
if err != nil {
fmt.Printf("delete vpn error: %+v\n", err)
return
}
fmt.Printf("delete vpn success\n")
Note:
- Release the specified VPN which cannot be retrieved
- If you want to release the prepaid VPN in advance, please proceed with the work order.
Bind EIP
Use the following code to bind EIP to VPN.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.BindEipArgs{
ClientToken: ClientToken(),
Eip: Eip,
}
err := client.BindEip(vpnId, args)
if err != nil {
fmt.Printf("bind eip error: %+v\n", err)
return
}
Note:
- EIP binding is an asynchronous process. You can check whether the binding is successful by querying the status of the VPN
Unbind EIP
Use the following code to unbind the VPN EIP.
// import "github.com/baidubce/bce-sdk-go/services/vpn"
if err := client.UnBindEip(vpnId, clientToken); err != nil {
fmt.Printf("unbind eip error: %+v\n", err)
return
}
fmt.Printf("unbind eip success.")
Note: Unbinding EIP is an asynchronous process, you can check whether the binding is successful by querying the status of the VPN
VPN gateway renewal
Use the following code to extend the expiration time of the VPN
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.RenewVpnGatewayArgs{
ClientToken: ClientToken,
Billing: &Billing{
Reservation: &Reservation{
ReservationLength: 1,
ReservationTimeUnit: "month",
},
},
}
if err := client.RenewVpnGateway(vpnId, args); err != nil {
fmt.Printf(" renew vpn error: %+v\n", err)
return
}
fmt.Printf("renew vpn success.")
Note:
- Only prepaid resources can be renewed.
Create a VPN tunnel
Use the following code to create a tunnel for the specified VPN
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.CreateVpnConnArgs{
VpnId: VpnId,
VpnConnName: VpnConnName,
LocalIp: LocalIp,
SecretKey: SecretKey,
LocalSubnets: []string{"subnet"},
RemoteIp: RemoteIp,
RemoteSubnets: []string{"RemoteSubnet"},
CreateIkeConfig: &CreateIkeConfig{
IkeVersion: "v1",
IkeMode: "main",
IkeEncAlg: "aes",
IkeAuthAlg: "sha1",
IkePfs: "group2",
IkeLifeTime: 25500,
},
CreateIpsecConfig: &CreateIpsecConfig{
IpsecEncAlg: "aes",
IpsecAuthAlg: "sha1",
IpsecPfs: "group2",
IpsecLifetime: 25500,
},
}
res, err := client.CreateVpnConn(args)
if err != nil {
fmt.Printf(" create vpnconn error: %+v\n", err)
return
}
fmt.Printf(" create vpnconn success,connId is: %+v",res.VpnConnId)
Query the VPN tunnel
Use the following code to query the tunnel information of the specified VPN
// import "github.com/baidubce/bce-sdk-go/services/vpn"
result,err:=vpn.ListVpnConn("vpnId")
if err != nil {
fmt.Printf("get vpn detail error: %+v\n", err)
return
}
for _, e := range result.VpnConns {
fmt.Println("vpnconn Id: ", e.VpnConnId)
fmt.Println("vpnconn LocalIp: ",e.LocalIp)
fmt.Println("vpnconn Description: ",e.Description)
fmt.Println("vpnconn CreatedTime: ",e.CreatedTime)
fmt.Println("vpnconn HealthStatus: ",e.HealthStatus)
fmt.Println("vpnconn LocalIp: ",e.LocalIp)
fmt.Println("vpnconn LocalSubnets: ",e.LocalSubnets)
fmt.Println("vpnconn RemoteSubnets: ",e.RemoteSubnets)
fmt.Println("vpnconn IkeConfig: ",e.IkeConfig)
fmt.Println("vpnconn IpsecConfig: ",e.IpsecConfig)
}
Update a VPN tunnel
Use the following code to modify the specified VPN tunnel
// import "github.com/baidubce/bce-sdk-go/services/vpn"
args := &vpn.UpdateVpnConnArgs{
vpnConnId: vpnConnId,
updateVpnconn: &CreateVpnConnArgs{
VpnId: VpnId,
VpnConnName: VpnConnName,
LocalIp: LocalIp,
SecretKey: SecretKey,
LocalSubnets: []string{"LocalSubnets"},
RemoteIp: RemoteIp,
RemoteSubnets: []string{"RemoteSubnets"},
CreateIkeConfig: &CreateIkeConfig{
IkeVersion: "v1",
IkeMode: "main",
IkeEncAlg: "aes",
IkeAuthAlg: "sha1",
IkePfs: "group2",
IkeLifeTime: 25500,
},
CreateIpsecConfig: &CreateIpsecConfig{
IpsecEncAlg: "aes",
IpsecAuthAlg: "sha1",
IpsecPfs: "group2",
IpsecLifetime: 25500,
},
},
}
err := client.UpdateVpnConn(args)
if err != nil {
fmt.Printf(" uodate vpnconn error: %+v\n", err)
return
}
fmt.Printf(" update vpnconn success,connId is: %+v",res.VpnConnId)
Delete a VPN tunnel
// import "github.com/baidubce/bce-sdk-go/services/vpn"
err = client.DeleteVpnConn(vpnconnId, clientToken)
if err != nil {
fmt.Printf("delete vpnconn error: %+v\n", err)
return
}
fmt.Printf("delete vpnconn success\n")
Error handling
GO language marks error with error type, and VPN supports 2 errors in the table below:
Error type | Description |
---|---|
BceClientError | Error arising from user operation |
BceServiceError | Error returned by VPN service |
You call VPN related interface with SDK, in addition to the results required, error is returned, and users can get relevant errors for handling. Instance is as follows”
// vpnClient is a created VPN Client object.
args := &vpn.ListVpnGatewayArgs{}
result, err := client.ListVpnGateway(args)
if err != nil {
switch realErr := err.(type) {
case *bce.BceClientError:
fmt.Println("client occurs error:", realErr.Error())
case *bce.BceServiceError:
fmt.Println("service occurs error:", realErr.Error())
default:
fmt.Println("unknown error:", err)
}
}
Client exception
Client exception indicates an exception encountered when the client attempts to send a request to the VPN and transmits data. For example, when the network connection is unavailable at the time of sending request, BceClientError is returned.
Server exception
When an exception occurs on the VPN server, the VPN server returns the corresponding error message to the user to locate the problem. For the common service end exceptions, please see VPN error code
SDK log
VPN GO SDK realizes the supporting of log module of 6 levels, 3 outputs (standard output, standard error and file) and basic format setting, with import path github.com/baidubce/bce-sdk-go/util/log
. When the output is file, setting of 5 log rolling modes (not rolling, by day, by hour, by minute and by size) is supported, and in this case, directory where the log file is output also needs to be set.
Default log
VPN GO SDK contains the global log object of package level, which does not record log by default, and if it is needed to output SDK related log, users need to specify the output mode and level, for details, please see the example below:
// import "github.com/baidubce/bce-sdk-go/util/log"
// Specify output to standard error, and output level of INFO and above
log.SetLogHandler(log.STDERR)
log.SetLogLevel(log.INFO)
// Specify output to standard error and file, DEBUG and above level, and roll by 1GB file size
log.SetLogHandler(log.STDERR| log.FILE)
log.SetLogDir("/tmp/gosdk-log")
log.SetRotateType(log.ROTATE_SIZE)
log.SetRotateSize(1 << 30)
// Output to standard output, and only output level and log message
log.SetLogHandler(log.STDOUT)
log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG})
Description:
- The default output level of log is
DEBUG
- If the output is set to file, the default log output directory is
/tmp
, and rolled by hour by default. - If the output is set to file and rolled by size, the rolling size is 1GB by default.
- The default log output format is:
FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG
Use of project
The log module does not have any external reliance, and users can directly refer to that log module in the project when using GO SDK developing project; users can continue to use the log object of package level used by GO SDK, and also can create a log object, see the example below:
// Use global log object of package level directly (output together with GO SDK own log)
log.SetLogHandler(log.STDERR)
log.Debugf("%s", "logging message using the log package in the VPN go sdk")
// Create a log object (set output log based on customization, separated with GO SDK log output)
myLogger := log.NewLogger()
myLogger.SetLogHandler(log.FILE)
myLogger.SetLogDir("/home/log")
myLogger.SetRotateType(log.ROTATE_SIZE)
myLogger.Info("this is my own logger from the VPN go sdk")