Skip to content

Commit

Permalink
Remove deprecated usage in the examples (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
chkp-royl authored Jul 24, 2024
1 parent afb5b18 commit b268ce0
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 83 deletions.
56 changes: 28 additions & 28 deletions APIFiles/APIClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ import (
)

const (
InProgress string = "in progress"
DefaultPort int = 443
Limit int = 50
Filename string = "fingerprints.json"
TimeOut time.Duration = time.Second * 10
SleepTime time.Duration = time.Second * 2
GaiaContext string = "gaia_api"
WebContext string = "web_api"
DefaultProxyPort = -1
DefaultProxyHost = ""
AutoPublishBatchSize int = 100
InProgress string = "in progress"
DefaultPort int = 443
Limit int = 50
Filename string = "fingerprints.json"
TimeOut time.Duration = time.Second * 10
SleepTime time.Duration = time.Second * 2
GaiaContext string = "gaia_api"
WebContext string = "web_api"
DefaultProxyPort = -1
DefaultProxyHost = ""
AutoPublishBatchSize int = 100
)

// Check Point API Client (Management/GAIA)
Expand All @@ -66,15 +66,15 @@ type ApiClient struct {
userAgent string
cloudMgmtId string
autoPublishBatchSize int
activeCallsLock sync.Mutex
autoPublishLock sync.Mutex
totalCallsLock sync.Mutex
activeCallsLock sync.Mutex
autoPublishLock sync.Mutex
totalCallsLock sync.Mutex
duringPublish bool
activeCallsCtr int
totalCallsCtr int
activeCallsCtr int
totalCallsCtr int
}

// Api Client constructor
// ApiClient constructor
// Input ApiClientArgs
// Returns new client instance
func APIClient(apiCA ApiClientArgs) *ApiClient {
Expand Down Expand Up @@ -212,7 +212,7 @@ func (c *ApiClient) DisableAutoPublish() {
c.totalCallsCtr = 0
}

// Deprecated: Do not use.
// Deprecated: Do not use. Use ApiLogin instead
func (c *ApiClient) Login(username string, password string, continueLastSession bool, domain string, readOnly bool, payload string) (APIResponse, error) {
credentials := map[string]interface{}{
"user": username,
Expand All @@ -221,7 +221,7 @@ func (c *ApiClient) Login(username string, password string, continueLastSession
return c.commonLoginLogic(credentials, continueLastSession, domain, readOnly, make(map[string]interface{}))
}

// Deprecated: Do not use.
// Deprecated: Do not use. Use ApiLoginWithApiKey instead
func (c *ApiClient) LoginWithApiKey(apiKey string, continueLastSession bool, domain string, readOnly bool, payload string) (APIResponse, error) {
credentials := map[string]interface{}{
"api-key": apiKey,
Expand All @@ -230,7 +230,7 @@ func (c *ApiClient) LoginWithApiKey(apiKey string, continueLastSession bool, dom
}

/*
Performs a 'login' API call to management server
Performs login API call to the management server using username and password
username: Check Point admin name
password: Check Point admin password
Expand All @@ -251,7 +251,7 @@ func (c *ApiClient) ApiLogin(username string, password string, continueLastSessi
}

/*
performs a 'login' API call to the management server
Performs login API call to the management server using api key
api_key: Check Point api-key
continue_last_session: [optional] It is possible to continue the last Check Point session
Expand Down Expand Up @@ -411,9 +411,9 @@ func (c *ApiClient) apiCall(command string, payload map[string]interface{}, sid
if !internal && c.autoPublishBatchSize > 0 {
waitToRun := true
for waitToRun {
if c.totalCallsCtr + 1 <= c.autoPublishBatchSize && !c.duringPublish {
if c.totalCallsCtr+1 <= c.autoPublishBatchSize && !c.duringPublish {
c.totalCallsLock.Lock()
if c.totalCallsCtr + 1 <= c.autoPublishBatchSize && !c.duringPublish {
if c.totalCallsCtr+1 <= c.autoPublishBatchSize && !c.duringPublish {
c.totalCallsCtr++
waitToRun = false
}
Expand Down Expand Up @@ -519,9 +519,9 @@ func (c *ApiClient) apiCall(command string, payload map[string]interface{}, sid

if !internal && c.autoPublishBatchSize > 0 {
c.decreaseActiveCalls()
if c.totalCallsCtr > 0 && c.totalCallsCtr % c.autoPublishBatchSize == 0 && !c.duringPublish {
if c.totalCallsCtr > 0 && c.totalCallsCtr%c.autoPublishBatchSize == 0 && !c.duringPublish {
c.autoPublishLock.Lock()
if c.totalCallsCtr > 0 && c.totalCallsCtr % c.autoPublishBatchSize == 0 && !c.duringPublish {
if c.totalCallsCtr > 0 && c.totalCallsCtr%c.autoPublishBatchSize == 0 && !c.duringPublish {
c.duringPublish = true
c.autoPublishLock.Unlock()
for c.activeCallsCtr > 0 {
Expand All @@ -531,16 +531,16 @@ func (c *ApiClient) apiCall(command string, payload map[string]interface{}, sid
}
// Going to publish
fmt.Println("Start auto publish...")
publishRes, _ := c.apiCall("publish", map[string]interface{}{},c.GetSessionID(),true,c.IsProxyUsed(), true)
publishRes, _ := c.apiCall("publish", map[string]interface{}{}, c.GetSessionID(), true, c.IsProxyUsed(), true)

if !publishRes.Success {
fmt.Println("Auto publish failed. Message: " + publishRes.ErrorMsg)
}else{
} else {
fmt.Println("Auto publish finished successfully")
}
c.totalCallsCtr = 0
c.duringPublish = false
}else{
} else {
c.autoPublishLock.Unlock()
}
}
Expand Down
44 changes: 21 additions & 23 deletions APIFiles/APIClientArgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package api_go_sdk

import "time"

// Api Client arguments to init a new instance
// ApiClient arguments to init a new instance
type ApiClientArgs struct {
Port int
Fingerprint string
Expand All @@ -16,16 +16,15 @@ type ApiClientArgs struct {
AcceptServerCertificate bool
DebugFile string
Context string
Timeout time.Duration
Sleep time.Duration
UserAgent string
Timeout time.Duration
Sleep time.Duration
UserAgent string
CloudMgmtId string
AutoPublishBatchSize int
AutoPublishBatchSize int
}

/*
Init a new APIClientArgs
Construct a new ApiClientArgs instance with the given parameters.
Init new APIClientArgs
Port: the port that is being used
Fingerprint: server's fingerprint
Expand All @@ -42,26 +41,25 @@ Timeout: HTTP Client timeout value
Sleep: Interval size in seconds of the task update
UserAgent: User agent will be use in api call request header
CloudMgmtId: Smart-1 Cloud management UID
AutoPublishBatchSize: Number of batch size for auto publish
AutoPublishBatchSize: Publish will run automatically on every 'X' number of api calls, set -1 (or any negative number) to disable the feature
*/
func APIClientArgs(port int, fingerprint string, sid string, server string, proxyHost string, proxyPort int, apiVersion string, ignoreServerCertificate bool, acceptServerCertificate bool, debugFile string, context string, timeout time.Duration, sleep time.Duration, userAgent string, cloudMgmtId string, autoPublishBatchSize int) ApiClientArgs {

return ApiClientArgs{
Port: port,
Fingerprint: fingerprint,
Sid: sid,
Server: server,
ProxyHost: proxyHost,
ProxyPort: proxyPort,
ApiVersion: apiVersion,
Port: port,
Fingerprint: fingerprint,
Sid: sid,
Server: server,
ProxyHost: proxyHost,
ProxyPort: proxyPort,
ApiVersion: apiVersion,
IgnoreServerCertificate: ignoreServerCertificate,
AcceptServerCertificate: acceptServerCertificate,
DebugFile: debugFile,
Context: context,
Timeout: timeout,
Sleep: sleep,
UserAgent: userAgent,
CloudMgmtId: cloudMgmtId,
AutoPublishBatchSize: autoPublishBatchSize,
DebugFile: debugFile,
Context: context,
Timeout: timeout,
Sleep: sleep,
UserAgent: userAgent,
CloudMgmtId: cloudMgmtId,
AutoPublishBatchSize: autoPublishBatchSize,
}
}
4 changes: 1 addition & 3 deletions Examples/add_access_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,12 @@ func AddAccessRule() {
os.Exit(1)
}

loginRes, err := client.Login(username, password, false, "", false, "")
loginRes, err := client.ApiLogin(username, password, false, "", false, nil)
if err != nil {
print("Login error.\n")
os.Exit(1)
}



if loginRes.Success == false {
print("Login failed:\n" + loginRes.ErrorMsg)
os.Exit(1)
Expand Down
2 changes: 1 addition & 1 deletion Examples/add_host.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func AddHost() {
os.Exit(1)
}

loginRes, err := client.Login(username, password,false, "", false, "")
loginRes, err := client.ApiLogin(username, password, false, "", false, nil)
if err != nil {
print("Login error.\n")
os.Exit(1)
Expand Down
33 changes: 18 additions & 15 deletions Examples/auto_publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import (
"time"
)

// This program demonstrates auto publish feature
// Publish will run automatically on every 'X' number of api calls, set 'autoPublishBatchSize' to -1 (or any negative number) to disable the feature
// In this program, 10 threads runs in parallel, each thread create 20 group objects, auto publish runs on every 100 created objects
func AutoPublish() {
numOfThreads := 10 // Total number of threads
numOfObjectsToCreate := 20 // Total number of objects to create by each thread
autoPublishBatchSize := api.AutoPublishBatchSize // Call publish on every 100 api calls
threadNamePrefix := "auto-publish-thread"
var apiServer string
var username string
var password string
Expand All @@ -22,7 +29,7 @@ func AutoPublish() {
fmt.Printf("Enter password: ")
fmt.Scanln(&password)

args := api.APIClientArgs(api.DefaultPort, "", "", apiServer, "", -1, "", false, false, "deb.txt", api.WebContext, api.TimeOut, api.SleepTime, "", "", api.AutoPublishBatchSize)
args := api.APIClientArgs(api.DefaultPort, "", "", apiServer, "", -1, "", false, false, "deb.txt", api.WebContext, api.TimeOut, api.SleepTime, "", "", autoPublishBatchSize)

client := api.APIClient(args)

Expand All @@ -31,7 +38,7 @@ func AutoPublish() {
os.Exit(1)
}

loginRes, err := client.ApiLogin(username, password,false, "", false, nil)
loginRes, err := client.ApiLogin(username, password, false, "", false, nil)
if err != nil {
fmt.Println("Login error")
os.Exit(1)
Expand All @@ -42,34 +49,30 @@ func AutoPublish() {
os.Exit(1)
}

numOfThreads := 10
numOfObjectsToCreate := 20
threadNamePrefix := "auto-publish-thread"

fmt.Println("Start auto publish program. Number of threads " + strconv.Itoa(numOfThreads))
for i := 0; i < numOfThreads; i++ {
go run(threadNamePrefix + strconv.Itoa(i), numOfObjectsToCreate, client)
go run(threadNamePrefix+strconv.Itoa(i), numOfObjectsToCreate, client)
}

time.Sleep(time.Minute * 3)

client.ApiCallSimple("publish", map[string]interface{}{})
_, _ = client.ApiCallSimple("publish", map[string]interface{}{}) // publish leftovers if exists

fmt.Println("Finished to create all objects")

deleteObjects(client, threadNamePrefix)

client.ApiCallSimple("logout", map[string]interface{}{})
_, _ = client.ApiCallSimple("logout", map[string]interface{}{})

fmt.Println("Auto publish example finished successfully")
}

func run(threadName string, numOfObjectsToCreate int, apiClient interface{}){
func run(threadName string, numOfObjectsToCreate int, apiClient interface{}) {
fmt.Println("Start thread -> " + threadName)
client := apiClient.(*api.ApiClient)
for i := 0; i < numOfObjectsToCreate; i++ {
groupName := threadName + "-group" + strconv.Itoa(i)
res, err := client.ApiCallSimple("add-group", map[string]interface{}{"name":groupName})
res, err := client.ApiCallSimple("add-group", map[string]interface{}{"name": groupName})
if err != nil {
fmt.Println("Error: " + err.Error())
}
Expand All @@ -87,12 +90,12 @@ func deleteObjects(client *api.ApiClient, objPrefix string) {
objects := res.GetData()["objects"].([]map[string]interface{})
fmt.Println("Delete " + strconv.Itoa(len(objects)) + " objects...")
if len(objects) > 0 {
for i := 0 ; i < len(objects) ; i++ {
client.ApiCallSimple("delete-group", map[string]interface{}{"uid":objects[i]["uid"]})
for i := 0; i < len(objects); i++ {
client.ApiCallSimple("delete-group", map[string]interface{}{"uid": objects[i]["uid"]})
}
client.ApiCallSimple("publish", map[string]interface{}{})
client.ApiCallSimple("publish", map[string]interface{}{}) // publish leftovers if exists
fmt.Println("Groups deleted")
}else{
} else {
fmt.Println("Not found groups to delete")
}
}
Expand Down
6 changes: 3 additions & 3 deletions Examples/discard_sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func DiscardSessions() {
os.Exit(1)
}

loginRes, err := client.Login(username, password, false, "", false, "")
loginRes, err := client.ApiLogin(username, password, false, "", false, nil)
if err != nil {
print("Login error.\n")
os.Exit(1)
Expand Down Expand Up @@ -77,9 +77,9 @@ func DiscardSessions() {
discardRes, _ = client.ApiCall("discard", map[string]interface{}{"uid": sessionObj.(map[string]interface{})["uid"]}, "", false, false)

if discardRes.Success {
fmt.Println("Session " + sessionObj.(map[string]interface{})["uid"].(string)+ " discarded successfully")
fmt.Println("Session " + sessionObj.(map[string]interface{})["uid"].(string) + " discarded successfully")
} else {
fmt.Println("Session " + sessionObj.(map[string]interface{})["uid"].(string)+ " failed to discard")
fmt.Println("Session " + sessionObj.(map[string]interface{})["uid"].(string) + " failed to discard")
}
}

Expand Down
11 changes: 5 additions & 6 deletions Examples/find_dup_ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func DupIp() {
os.Exit(1)
}

loginRes, err := client.Login(username, pass, false, "", false, "")
loginRes, err := client.ApiLogin(username, pass, false, "", false, nil)
if err != nil {
print("Login error.\n")
os.Exit(1)
Expand All @@ -53,7 +53,7 @@ func DupIp() {
//dupIpSlice - a collection of the duplicate IP addresses in all the host objects.
var dupIpSlice []string

for _, host := range showHostsRes.GetData(){
for _, host := range showHostsRes.GetData() {
ipaddr := host.(map[string]interface{})["ipv4-address"].(string)
if ipaddr == "" {
print(host.(map[string]interface{})["name"].(string) + " has no IPv4 address. Skipping...")
Expand All @@ -65,7 +65,7 @@ func DupIp() {
if _, ok := objDictionary[ipaddr]; ok {
ipExists := false
for _, ip := range dupIpSlice {
if ip == ipaddr{
if ip == ipaddr {
ipExists = true
break
}
Expand All @@ -91,12 +91,12 @@ func DupIp() {
}

//for every duplicate ip - print hosts with that ip:
for _, dupIp := range dupIpSlice {
for _, dupIp := range dupIpSlice {

fmt.Println("\nIP Address: " + dupIp + "")
fmt.Println("-------------------------------")

for _, hostData := range objDictionary[dupIp]{
for _, hostData := range objDictionary[dupIp] {

fmt.Println("host name: " + hostData["name"] + " host uid: " + hostData["uid"])
//fmt.Println(hostData[1])
Expand All @@ -105,5 +105,4 @@ func DupIp() {

}


}
Loading

0 comments on commit b268ce0

Please sign in to comment.