├── .gitignore ├── LICENSE ├── README.md ├── action.go ├── action_test.go ├── event.go ├── go.mod ├── go.sum ├── history.go ├── history_test.go ├── host.go ├── host_test.go ├── hostgroup.go ├── hostgroup_test.go ├── hostinterface.go ├── hostinterface_test.go ├── mediatype.go ├── mediatype_test.go ├── problem.go ├── problem_test.go ├── template.go ├── template_test.go ├── user.go ├── user_test.go ├── usergroup.go ├── usergroup_test.go ├── usermacro.go ├── usermacro_test.go ├── zabbix.go └── zabbix_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .vscode 3 | .idea 4 | .env 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Nixys 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nxs-go-zabbix 2 | 3 | This Go package provides access to Zabbix API v5.0. 4 | Also see older versions in other branches. 5 | 6 | At the time not all Zabbix API methods are implemented, but work in progress. 7 | 8 | ## Install 9 | 10 | ``` 11 | go get github.com/nixys/nxs-go-zabbix/v5 12 | ``` 13 | 14 | ## Example of usage 15 | 16 | *You may find more examples in unit-tests in this repository* 17 | 18 | **Get all hosts on Zabbix server:** 19 | 20 | ```go 21 | package main 22 | 23 | import ( 24 | "fmt" 25 | "os" 26 | 27 | "github.com/nixys/nxs-go-zabbix/v5" 28 | ) 29 | 30 | func zabbixLogin(z *zabbix.Context, zbxHost, zbxUsername, zbxPassword string) { 31 | 32 | if err := z.Login(zbxHost, zbxUsername, zbxPassword); err != nil { 33 | fmt.Println("Login error:", err) 34 | os.Exit(1) 35 | } else { 36 | fmt.Println("Login: success") 37 | } 38 | } 39 | 40 | func zabbixLogout(z *zabbix.Context) { 41 | 42 | if err := z.Logout(); err != nil { 43 | fmt.Println("Logout error:", err) 44 | os.Exit(1) 45 | } else { 46 | fmt.Println("Logout: success") 47 | } 48 | } 49 | 50 | func main() { 51 | 52 | var z zabbix.Context 53 | 54 | /* Get variables from environment to login to Zabbix server */ 55 | zbxHost := os.Getenv("ZABBIX_HOST") 56 | zbxUsername := os.Getenv("ZABBIX_USERNAME") 57 | zbxPassword := os.Getenv("ZABBIX_PASSWORD") 58 | if zbxHost == "" || zbxUsername == "" || zbxPassword == "" { 59 | fmt.Println("Login error: make sure environment variables `ZABBIX_HOST`, `ZABBIX_USERNAME` and `ZABBIX_PASSWORD` are defined") 60 | os.Exit(1) 61 | } 62 | 63 | /* Login to Zabbix server */ 64 | zabbixLogin(&z, zbxHost, zbxUsername, zbxPassword) 65 | defer zabbixLogout(&z) 66 | 67 | /* Get all hosts */ 68 | hObjects, _, err := z.HostGet(zabbix.HostGetParams{ 69 | GetParameters: zabbix.GetParameters{ 70 | Output: zabbix.SelectExtendedOutput, 71 | }, 72 | }) 73 | if err != nil { 74 | fmt.Println("Hosts get error:", err) 75 | return 76 | } 77 | 78 | /* Print names of retrieved hosts */ 79 | fmt.Println("Hosts list:") 80 | for _, h := range hObjects { 81 | fmt.Println("-", h.Host) 82 | } 83 | } 84 | ``` 85 | 86 | Run: 87 | 88 | ``` 89 | ZABBIX_HOST="https://zabbix.yourdomain.com/api_jsonrpc.php" ZABBIX_USERNAME="Admin" ZABBIX_PASSWORD="PASSWORD" go run main.go 90 | ``` 91 | 92 | Test: 93 | 94 | ``` 95 | ZABBIX_HOST="https://zabbix.yourdomain.com/api_jsonrpc.php" ZABBIX_USERNAME="Admin" ZABBIX_PASSWORD="PASSWORD" go test -v -run TestProblemGet 96 | ``` 97 | 98 | 99 | ## Feedback 100 | 101 | For support and feedback please contact me: 102 | - telegram: [@borisershov](https://t.me/borisershov) 103 | - e-mail: b.ershov@nixys.ru 104 | 105 | ## License 106 | 107 | nxs-go-zabbix is released under the [MIT License](LICENSE). -------------------------------------------------------------------------------- /action.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `ActionObject` field: `Status` 4 | const ( 5 | ActionStatusEnabled = 0 6 | ActionStatusDisabled = 1 7 | ) 8 | 9 | // For `ActionObject` field: `PauseSuppressed` 10 | const ( 11 | ActionPauseSuppressedEnabled = 0 12 | ActionPauseSuppressedDisabled = 1 13 | ) 14 | 15 | // For `ActionOperationObject` field: `OperationType` 16 | const ( 17 | ActionOperationTypeSendMsg = 0 18 | ActionOperationTypeRemoteCmd = 1 19 | ActionOperationTypeAddHost = 2 20 | ActionOperationTypeRmHost = 3 21 | ActionOperationTypeAddToHostGroup = 4 22 | ActionOperationTypeRmFromHostGroup = 5 23 | ActionOperationTypeLinkToTpl = 6 24 | ActionOperationTypeUnlinkFromTpl = 7 25 | ActionOperationTypeEnableHost = 8 26 | ActionOperationTypeDisableHost = 9 27 | ActionOperationTypeSetHostInventoryMode = 10 28 | ) 29 | 30 | // For `ActionOperationObject` field: `EvalType` 31 | const ( 32 | ActionOperationEvalTypeAndOR = 0 33 | ActionOperationEvalTypeAnd = 1 34 | ActionOperationEvalTypeOr = 2 35 | ) 36 | 37 | // For `ActionOperationCommandObject` field: `Type` 38 | const ( 39 | ActionOperationCommandTypeCustomScript = 0 40 | ActionOperationCommandTypeIPMI = 1 41 | ActionOperationCommandTypeSSH = 2 42 | ActionOperationCommandTypeTelnet = 3 43 | ActionOperationCommandTypeGlobalScript = 4 44 | ) 45 | 46 | // For `ActionOperationCommandObject` field: `AuthType` 47 | const ( 48 | ActionOperationCommandAuthTypePassword = 0 49 | ActionOperationCommandAuthTypePubKey = 1 50 | ) 51 | 52 | // For `ActionOperationCommandObject` field: `ExecuteOn` 53 | const ( 54 | ActionOperationCommandExecuteOnAgent = 0 55 | ActionOperationCommandExecuteOnServer = 1 56 | ActionOperationCommandExecuteOnProxy = 2 57 | ) 58 | 59 | // For `ActionOperationMessageObject` field: `DefaultMsg` 60 | const ( 61 | ActionOperationMessageDefaultMsgFromOperation = 0 62 | ActionOperationMessageDefaultMsgFromMediaType = 1 63 | ) 64 | 65 | // For `ActionOperationConditionObject` field: `ConditionType` 66 | const ( 67 | ActionOperationConditionTypeEventAcknowledged = 14 68 | ) 69 | 70 | // For `ActionRecoveryOperationObject` field: `OperationType ` 71 | const ( 72 | ActionRecoveryOperationTypeSendMsg = 0 73 | ActionRecoveryOperationTypeRemoteCmd = 1 74 | ActionRecoveryOperationTypeNotifyAllInvolved = 11 75 | ) 76 | 77 | // For `ActionUpdateOperationObject` field: `OperationType ` 78 | const ( 79 | ActionUpdateOperationTypeSendMsg = 0 80 | ActionUpdateOperationTypeRemoteCmd = 1 81 | ActionUpdateOperationTypeNotifyAllInvolved = 12 82 | ) 83 | 84 | // For `ActionOperationConditionObject` field: `Operator` 85 | const ( 86 | ActionOperationConditionOperatorEq = 0 87 | ) 88 | 89 | // For `ActionFilterObject` field: `EvalType` 90 | const ( 91 | ActionFilterEvalTypeAndOr = 0 92 | ActionFilterEvalTypeAnd = 1 93 | ActionFilterEvalTypeOr = 2 94 | ActionFilterEvalTypeCustom = 3 95 | ) 96 | 97 | // For `ActionFilterConditionObject` field: `ConditionType` 98 | const ( 99 | ActionFilterConditionTypeHostroup = 0 100 | ActionFilterConditionTypeHost = 1 101 | ActionFilterConditionTypeTrigger = 2 102 | ActionFilterConditionTypeTriggerName = 3 103 | ActionFilterConditionTypeTriggerSeverity = 4 104 | ActionFilterConditionTypeTriggerValue = 5 105 | ActionFilterConditionTypeTimePeriod = 6 106 | ActionFilterConditionTypeHostIP = 7 107 | ActionFilterConditionTypeDiscoveryServiceType = 8 108 | ActionFilterConditionTypeDiscoveryServicePort = 9 109 | ActionFilterConditionTypeDiscoveryStatus = 10 110 | ActionFilterConditionTypeUpdownTimeDuration = 11 111 | ActionFilterConditionTypeRcvValue = 12 112 | ActionFilterConditionTypeHostTemplate = 13 113 | ActionFilterConditionTypeApplication = 15 114 | ActionFilterConditionTypeProblemIsSuppressed = 16 115 | ActionFilterConditionTypeDiscRule = 18 116 | ActionFilterConditionTypeDiscCheck = 19 117 | ActionFilterConditionTypeProxy = 20 118 | ActionFilterConditionTypeDiscObject = 21 119 | ActionFilterConditionTypeHostName = 22 120 | ActionFilterConditionTypeEventType = 23 121 | ActionFilterConditionTypeHostMetadata = 24 122 | ActionFilterConditionTypeTag = 25 123 | ActionFilterConditionTypeTagValue = 26 124 | ) 125 | 126 | // For `ActionFilterConditionObject` field: `Operator` 127 | const ( 128 | ActionFilterConditionOperatorEQ = 0 // = 129 | ActionFilterConditionOperatorNE = 1 // <> 130 | ActionFilterConditionOperatorContains = 2 // contains 131 | ActionFilterConditionOperatorNotrContain = 3 // does not contain 132 | ActionFilterConditionOperatorIN = 4 // in 133 | ActionFilterConditionOperatorGE = 5 // >= 134 | ActionFilterConditionOperatorLE = 6 // <= 135 | ActionFilterConditionOperatorNotIn = 7 // not in 136 | ActionFilterConditionOperatorMatches = 8 // matches 137 | ActionFilterConditionOperatorNotMatches = 9 // does not match 138 | ActionFilterConditionOperatorYes = 10 // yes 139 | ActionFilterConditionOperatorNo = 11 // no 140 | ) 141 | 142 | // ActionObject struct is used to store action operations results 143 | // 144 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action 145 | type ActionObject struct { 146 | ActionID int `json:"actionid,omitempty"` 147 | EscPeriod int `json:"esc_period"` 148 | Eventsource int `json:"eventsource"` 149 | Name string `json:"name"` 150 | Status int `json:"status,omitempty"` // has defined consts, see above 151 | PauseSuppressed int `json:"pause_suppressed,omitempty"` // has defined consts, see above 152 | 153 | Operations []ActionOperationObject `json:"operations,omitempty"` 154 | Filter ActionFilterObject `json:"filter,omitempty"` 155 | RecoveryOperations []ActionRecoveryOperationObject `json:"recovery_operations,omitempty"` 156 | AcknowledgeOperations []ActionRecoveryOperationObject `json:"acknowledge_operations,omitempty"` 157 | } 158 | 159 | // ActionOperationObject struct is used to store action operations 160 | // 161 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_operation 162 | type ActionOperationObject struct { 163 | OperationID int `json:"operationid,omitempty"` 164 | OperationType int `json:"operationtype"` // has defined consts, see above 165 | ActionID int `json:"actionid,omitempty"` 166 | EscPeriod int `json:"esc_period,omitempty"` 167 | EscStepFrom int `json:"esc_step_from,omitempty"` 168 | EscStepTo int `json:"esc_step_to,omitempty"` 169 | EvalType int `json:"evaltype,omitempty"` // has defined consts, see above 170 | Opcommand ActionOperationCommandObject `json:"opcommand,omitempty"` 171 | OpcommandGrp []ActionOpcommandGrpObject `json:"opcommand_grp,omitempty"` 172 | OpcommandHst []ActionOpcommandHstObject `json:"opcommand_hst,omitempty"` 173 | Opconditions []ActionOperationConditionObject `json:"opconditions,omitempty"` 174 | Opgroup []ActionOpgroupObject `json:"opgroup,omitempty"` 175 | Opmessage ActionOperationMessageObject `json:"opmessage,omitempty"` 176 | OpmessageGrp []ActionOpmessageGrpObject `json:"opmessage_grp,omitempty"` 177 | OpmessageUsr []ActionOpmessageUsrObject `json:"opmessage_usr,omitempty"` 178 | Optemplate []ActionOptemplateObject `json:"optemplate,omitempty"` 179 | Opinventory ActionOpinventoryObject `json:"opinventory,omitempty"` 180 | } 181 | 182 | // ActionOperationCommandObject struct is used to store action operation commands 183 | // 184 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_operation_command 185 | type ActionOperationCommandObject struct { 186 | Command string `json:"command"` 187 | Type int `json:"type"` // has defined consts, see above 188 | AuthType int `json:"authtype,omitempty"` // has defined consts, see above 189 | ExecuteOn int `json:"execute_on,omitempty"` // has defined consts, see above 190 | Password string `json:"password,omitempty"` 191 | Port string `json:"port,omitempty"` 192 | PrivateKey string `json:"privatekey,omitempty"` 193 | PublicKey string `json:"publickey,omitempty"` 194 | ScriptID int `json:"scriptid,omitempty"` 195 | UserName string `json:"username,omitempty"` 196 | } 197 | 198 | // ActionOperationMessageObject struct is used to store action operation messages 199 | // 200 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_operation_message 201 | type ActionOperationMessageObject struct { 202 | DefaultMsg int `json:"default_msg,omitempty"` // has defined consts, see above 203 | MediatypeID int `json:"mediatypeid,omitempty"` 204 | Message string `json:"message,omitempty"` 205 | Subject string `json:"subject,omitempty"` 206 | } 207 | 208 | // ActionOperationConditionObject struct is used to store action operation conditions 209 | // 210 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_operation_condition 211 | type ActionOperationConditionObject struct { 212 | OpconditionID int `json:"opconditionid,omitempty"` 213 | ConditionType int `json:"conditiontype"` // has defined consts, see above 214 | Value string `json:"value"` 215 | OperationID int `json:"operationid,omitempty"` 216 | Operator int `json:"operator,omitempty"` 217 | } 218 | 219 | // ActionRecoveryOperationObject struct is used to store action recovery operations 220 | // 221 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_recovery_operation 222 | type ActionRecoveryOperationObject struct { 223 | OperationID int `json:"operationid"` 224 | OperationType int `json:"operationtype,omitempty"` // has defined consts, see above 225 | ActionID int `json:"actionid,omitempty"` 226 | Opcommand ActionOperationCommandObject `json:"opcommand,omitempty"` 227 | OpcommandGrp []ActionOpcommandGrpObject `json:"opcommand_grp,omitempty"` 228 | OpcommandHst []ActionOpcommandHstObject `json:"opcommand_hst,omitempty"` 229 | Opmessage ActionOperationMessageObject `json:"opmessage,omitempty"` 230 | OpmessageGrp []ActionOpmessageGrpObject `json:"opmessage_grp,omitempty"` 231 | OpmessageUsr []ActionOpmessageUsrObject `json:"opmessage_usr,omitempty"` 232 | } 233 | 234 | // ActionUpdateOperationObject struct is used to store action update operations 235 | // 236 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_update_operation 237 | type ActionUpdateOperationObject struct { 238 | OperationID int `json:"operationid"` 239 | OperationType int `json:"operationtype,omitempty"` // has defined consts, see above 240 | Opcommand ActionOperationCommandObject `json:"opcommand,omitempty"` 241 | OpcommandGrp []ActionOpcommandGrpObject `json:"opcommand_grp,omitempty"` 242 | OpcommandHst []ActionOpcommandHstObject `json:"opcommand_hst,omitempty"` 243 | Opmessage ActionOperationMessageObject `json:"opmessage,omitempty"` 244 | OpmessageGrp []ActionOpmessageGrpObject `json:"opmessage_grp,omitempty"` 245 | OpmessageUsr []ActionOpmessageUsrObject `json:"opmessage_usr,omitempty"` 246 | } 247 | 248 | // ActionFilterObject struct is used to store action filters 249 | // 250 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_filter 251 | type ActionFilterObject struct { 252 | Conditions []ActionFilterConditionObject `json:"conditions"` 253 | EvalType int `json:"evaltype"` // has defined consts, see above 254 | EvalFormula string `json:"eval_formula,omitempty"` 255 | Formula string `json:"formula,omitempty"` 256 | } 257 | 258 | // ActionFilterConditionObject struct is used to store action filter conditions 259 | // 260 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/object#action_filter_condition 261 | type ActionFilterConditionObject struct { 262 | ConditionID int `json:"conditionid,omitempty"` 263 | ConditionType int `json:"conditiontype"` // has defined consts, see above 264 | Value string `json:"value"` 265 | Value2 string `json:"value2,omitempty"` 266 | ActionID int `json:"actionid,omitempty"` 267 | FormulaID string `json:"formulaid,omitempty"` 268 | Operator int `json:"operator,omitempty"` // has defined consts, see above 269 | } 270 | 271 | // ActionOpcommandGrpObject struct is used to store action opcommand groups 272 | type ActionOpcommandGrpObject struct { 273 | OpcommandGrpID int `json:"opcommand_grpid,omitempty"` 274 | OperationID int `json:"operationid,omitempty"` 275 | GroupID int `json:"groupid,omitempty"` 276 | } 277 | 278 | // ActionOpcommandHstObject struct is used to store action opcommand hosts 279 | type ActionOpcommandHstObject struct { 280 | OpcommandHstID int `json:"opcommand_hstid,omitempty"` 281 | OperationID int `json:"operationid,omitempty"` 282 | HostID int `json:"hostid,omitempty"` 283 | } 284 | 285 | // ActionOpgroupObject struct is used to store action opgroups 286 | type ActionOpgroupObject struct { 287 | OperationID int `json:"operationid,omitempty"` 288 | GroupID int `json:"groupid,omitempty"` 289 | } 290 | 291 | // ActionOpmessageGrpObject struct is used to store action opmessage groups 292 | type ActionOpmessageGrpObject struct { 293 | OperationID int `json:"operationid,omitempty"` 294 | UsrgrpID int `json:"usrgrpid,omitempty"` 295 | } 296 | 297 | // ActionOpmessageUsrObject struct is used to store action opmessage users 298 | type ActionOpmessageUsrObject struct { 299 | OperationID int `json:"operationid,omitempty"` 300 | UserID int `json:"userid,omitempty"` 301 | } 302 | 303 | // ActionOptemplateObject struct is used to store action optemplates 304 | type ActionOptemplateObject struct { 305 | OperationID int `json:"operationid,omitempty"` 306 | TemplateID int `json:"templateid,omitempty"` 307 | } 308 | 309 | // ActionOpinventoryObject struct is used to store action opinventory 310 | type ActionOpinventoryObject struct { 311 | OperationID int `json:"operationid,omitempty"` 312 | InventoryMode int `json:"inventory_mode,omitempty"` 313 | } 314 | 315 | // ActionGetParams struct is used for action get requests 316 | // 317 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/action/get#parameters 318 | type ActionGetParams struct { 319 | GetParameters 320 | 321 | ActionIDs []int `json:"actionids,omitempty"` 322 | GroupIDs []int `json:"groupids,omitempty"` 323 | HostIDs []int `json:"hostids,omitempty"` 324 | TriggerIDs []int `json:"triggerids,omitempty"` 325 | MediatypeIDs []int `json:"mediatypeids,omitempty"` 326 | UsrgrpIDs []int `json:"usrgrpids,omitempty"` 327 | UserIDs []int `json:"userids,omitempty"` 328 | ScriptIDs []int `json:"scriptids,omitempty"` 329 | 330 | SelectFilter SelectQuery `json:"selectFilter,omitempty"` 331 | SelectOperations SelectQuery `json:"selectOperations,omitempty"` 332 | SelectRecoveryOperations SelectQuery `json:"selectRecoveryOperations,omitempty"` 333 | SelectUpdateOperations SelectQuery `json:"selectUpdateOperations,omitempty"` 334 | } 335 | 336 | // Structure to store creation result 337 | type actionCreateResult struct { 338 | ActionIDs []int `json:"actionids"` 339 | } 340 | 341 | // Structure to store deletion result 342 | type actionDeleteResult struct { 343 | ActionIDs []int `json:"actionids"` 344 | } 345 | 346 | // ActionGet gets actions 347 | func (z *Context) ActionGet(params ActionGetParams) ([]ActionObject, int, error) { 348 | 349 | var result []ActionObject 350 | 351 | status, err := z.request("action.get", params, &result) 352 | if err != nil { 353 | return nil, status, err 354 | } 355 | 356 | return result, status, nil 357 | } 358 | 359 | // ActionCreate creates actions 360 | func (z *Context) ActionCreate(params []ActionObject) ([]int, int, error) { 361 | 362 | var result actionCreateResult 363 | 364 | status, err := z.request("action.create", params, &result) 365 | if err != nil { 366 | return nil, status, err 367 | } 368 | 369 | return result.ActionIDs, status, nil 370 | } 371 | 372 | // ActionDelete deletes actions 373 | func (z *Context) ActionDelete(actionIDs []int) ([]int, int, error) { 374 | 375 | var result actionDeleteResult 376 | 377 | status, err := z.request("action.delete", actionIDs, &result) 378 | if err != nil { 379 | return nil, status, err 380 | } 381 | 382 | return result.ActionIDs, status, nil 383 | } 384 | -------------------------------------------------------------------------------- /action_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "strconv" 6 | "testing" 7 | ) 8 | 9 | const ( 10 | testActionName = "testAction" 11 | testActionEscPeriod = 300 12 | testActionDefShortdata = "{HOST.NAME1} [{TRIGGER.STATUS}]: {TRIGGER.NAME}" 13 | testActionDefLongdata = "Trigger: {TRIGGER.NAME}\r\nTrigger status: {TRIGGER.STATUS}\r\nTrigger severity: {TRIGGER.SEVERITY}\r\nTrigger URL: {TRIGGER.URL}\r\nEvent type: E1\r\n\r\nItem values:\r\n\r\n1. {ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): {ITEM.VALUE1}\r\n2. {ITEM.NAME2} ({HOST.NAME2}:{ITEM.KEY2}): {ITEM.VALUE2}\r\n3. {ITEM.NAME3} ({HOST.NAME3}:{ITEM.KEY3}): {ITEM.VALUE3}\r\n\r\nOriginal event ID: {EVENT.ID}" 14 | testMediaTypeID = 1 15 | ) 16 | 17 | func TestActionCRUD(t *testing.T) { 18 | 19 | var z Context 20 | 21 | // Login 22 | loginTest(&z, t) 23 | defer logoutTest(&z, t) 24 | 25 | // Preparing auxiliary data 26 | hgCreatedIDs := testHostgroupCreate(t, z) 27 | defer testHostgroupDelete(t, z, hgCreatedIDs) 28 | 29 | // Create and delete 30 | aCreatedIDs := testActionCreate(t, z, hgCreatedIDs[0], 7) 31 | defer testActionDelete(t, z, aCreatedIDs) 32 | 33 | // Get 34 | testActionGet(t, z, aCreatedIDs) 35 | } 36 | 37 | func testActionCreate(t *testing.T, z Context, hostgrpID, usergrpID int) []int { 38 | 39 | aCreatedIDs, _, err := z.ActionCreate([]ActionObject{ 40 | { 41 | Name: testActionName, 42 | Eventsource: 0, 43 | Status: ActionStatusEnabled, 44 | EscPeriod: testActionEscPeriod, 45 | Filter: ActionFilterObject{ 46 | EvalType: ActionFilterEvalTypeAndOr, 47 | Conditions: []ActionFilterConditionObject{ 48 | { 49 | ConditionType: ActionFilterConditionTypeProblemIsSuppressed, 50 | Operator: ActionFilterConditionOperatorNo, 51 | }, 52 | { 53 | ConditionType: ActionFilterConditionTypeHostroup, 54 | Operator: ActionFilterConditionOperatorEQ, 55 | Value: strconv.Itoa(hostgrpID), 56 | }, 57 | }, 58 | }, 59 | Operations: []ActionOperationObject{ 60 | { 61 | OperationType: ActionOperationTypeSendMsg, 62 | EscPeriod: 0, 63 | EscStepFrom: 2, 64 | EscStepTo: 2, 65 | EvalType: ActionOperationEvalTypeAndOR, 66 | Opconditions: []ActionOperationConditionObject{ 67 | { 68 | ConditionType: ActionOperationConditionTypeEventAcknowledged, 69 | Operator: ActionOperationConditionOperatorEq, 70 | Value: "0", 71 | }, 72 | }, 73 | Opmessage: ActionOperationMessageObject{ 74 | DefaultMsg: ActionOperationMessageDefaultMsgFromOperation, 75 | MediatypeID: testMediaTypeID, 76 | }, 77 | OpmessageGrp: []ActionOpmessageGrpObject{ 78 | { 79 | UsrgrpID: usergrpID, 80 | }, 81 | }, 82 | }, 83 | }, 84 | }, 85 | }) 86 | 87 | if err != nil { 88 | t.Fatal("Action create error:", err) 89 | } 90 | 91 | if len(aCreatedIDs) == 0 { 92 | t.Fatal("Action create error: empty IDs array") 93 | } 94 | 95 | t.Logf("Action create: success") 96 | 97 | return aCreatedIDs 98 | } 99 | 100 | func testActionDelete(t *testing.T, z Context, aCreatedIDs []int) []int { 101 | 102 | aDeletedIDs, _, err := z.ActionDelete(aCreatedIDs) 103 | if err != nil { 104 | t.Fatal("Action delete error:", err) 105 | } 106 | 107 | if len(aDeletedIDs) == 0 { 108 | t.Fatal("Action delete error: empty IDs array") 109 | } 110 | 111 | if reflect.DeepEqual(aDeletedIDs, aCreatedIDs) == false { 112 | t.Fatal("Action delete error: IDs arrays for created and deleted action are mismatch") 113 | } 114 | 115 | t.Logf("Action delete: success") 116 | 117 | return aDeletedIDs 118 | } 119 | 120 | func testActionGet(t *testing.T, z Context, aCreatedIDs []int) []ActionObject { 121 | 122 | aObjects, _, err := z.ActionGet(ActionGetParams{ 123 | SelectOperations: SelectExtendedOutput, 124 | SelectFilter: SelectExtendedOutput, 125 | ActionIDs: aCreatedIDs, 126 | GetParameters: GetParameters{ 127 | Filter: map[string]interface{}{ 128 | "name": testActionName, 129 | }, 130 | Output: SelectExtendedOutput, 131 | }, 132 | }) 133 | 134 | if err != nil { 135 | t.Error("Action get error:", err) 136 | } else { 137 | if len(aObjects) == 0 { 138 | t.Error("Action get error: unable to find created action") 139 | } else { 140 | t.Logf("Action get: success") 141 | } 142 | } 143 | 144 | return aObjects 145 | } 146 | -------------------------------------------------------------------------------- /event.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | type EventAcknowledgeActionType int64 4 | 5 | const ( 6 | EventAcknowledgeActionTypeClose EventAcknowledgeActionType = 1 7 | EventAcknowledgeActionTypeAck EventAcknowledgeActionType = 2 8 | EventAcknowledgeActionTypeAddMessage EventAcknowledgeActionType = 4 9 | EventAcknowledgeActionTypeChangeSeverity EventAcknowledgeActionType = 8 10 | EventAcknowledgeActionTypeUnack EventAcknowledgeActionType = 16 11 | EventAcknowledgeActionTypeSuppress EventAcknowledgeActionType = 32 12 | EventAcknowledgeActionTypeUnsuppress EventAcknowledgeActionType = 64 13 | EventAcknowledgeActionTypeChangeEventRankCause EventAcknowledgeActionType = 128 14 | EventAcknowledgeActionTypeChangeEventRankSymptom EventAcknowledgeActionType = 256 15 | ) 16 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/nixys/nxs-go-zabbix/v5 2 | 3 | go 1.20 4 | 5 | require github.com/mitchellh/mapstructure v1.5.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/mitchellh/mapstructure v1.3.0 h1:iDwIio/3gk2QtLLEsqU5lInaMzos0hDTz8a6lazSFVw= 2 | github.com/mitchellh/mapstructure v1.3.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 3 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 4 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 5 | -------------------------------------------------------------------------------- /history.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import "fmt" 4 | 5 | // For `HistoryGetParams` field: `History` 6 | const ( 7 | HistoryObjectTypeFloat = 0 8 | HistoryObjectTypeCharacter = 1 9 | HistoryObjectTypeLog = 2 10 | HistoryObjectTypeNumericUnsigned = 3 11 | HistoryObjectTypeText = 4 12 | ) 13 | 14 | // HistoryFloatObject struct is used to store history float operations results 15 | // 16 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/history/object#float_history 17 | type HistoryFloatObject struct { 18 | Clock int `json:"clock,omitempty"` 19 | ItemID int `json:"itemid,omitempty"` 20 | NS int `json:"ns,omitempty"` 21 | Value float64 `json:"value,omitempty"` 22 | } 23 | 24 | // HistoryIntegerObject struct is used to store history integer operations results 25 | // 26 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/history/object#integer_history 27 | type HistoryIntegerObject struct { 28 | Clock int `json:"clock,omitempty"` 29 | ItemID int `json:"itemid,omitempty"` 30 | NS int `json:"ns,omitempty"` 31 | Value int `json:"value,omitempty"` 32 | } 33 | 34 | // HistoryStringObject struct is used to store history string operations results 35 | // 36 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/history/object#string_history 37 | type HistoryStringObject struct { 38 | Clock int `json:"clock,omitempty"` 39 | ItemID int `json:"itemid,omitempty"` 40 | NS int `json:"ns,omitempty"` 41 | Value string `json:"value,omitempty"` 42 | } 43 | 44 | // HistoryTextObject struct is used to store history text operations results 45 | // 46 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/history/object#text_history 47 | type HistoryTextObject struct { 48 | ID int `json:"id,omitempty"` 49 | Clock int `json:"clock,omitempty"` 50 | ItemID int `json:"itemid,omitempty"` 51 | NS int `json:"ns,omitempty"` 52 | Value string `json:"value,omitempty"` 53 | } 54 | 55 | // HistoryLogObject struct is used to store history log operations results 56 | // 57 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/history/object#log_history 58 | type HistoryLogObject struct { 59 | ID int `json:"id,omitempty"` 60 | Clock int `json:"clock,omitempty"` 61 | ItemID int `json:"itemid,omitempty"` 62 | LogeventID int `json:"logeventid,omitempty"` 63 | NS int `json:"ns,omitempty"` 64 | Severity int `json:"severity,omitempty"` 65 | Source int `json:"source,omitempty"` 66 | Timestamp int `json:"timestamp,omitempty"` 67 | Value string `json:"value,omitempty"` 68 | } 69 | 70 | // HistoryGetParams struct is used for history get requests 71 | // 72 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/history/get#parameters 73 | type HistoryGetParams struct { 74 | GetParameters 75 | 76 | History int `json:"history"` // has defined consts, see above 77 | HostIDs []int `json:"hostids,omitempty"` 78 | ItemIDs []int `json:"itemids,omitempty"` 79 | TimeFrom int `json:"time_from,omitempty"` 80 | TimeTill int `json:"time_till,omitempty"` 81 | 82 | Sortfield string `json:"sortfield,omitempty"` 83 | } 84 | 85 | // HistoryGet gets history 86 | func (z *Context) HistoryGet(params HistoryGetParams) (interface{}, int, error) { 87 | 88 | var result interface{} 89 | 90 | switch params.History { 91 | case HistoryObjectTypeFloat: 92 | result = &([]HistoryFloatObject{}) 93 | case HistoryObjectTypeCharacter: 94 | result = &([]HistoryStringObject{}) 95 | case HistoryObjectTypeLog: 96 | result = &([]HistoryLogObject{}) 97 | case HistoryObjectTypeNumericUnsigned: 98 | result = &([]HistoryIntegerObject{}) 99 | case HistoryObjectTypeText: 100 | result = &([]HistoryTextObject{}) 101 | default: 102 | return nil, 0, fmt.Errorf("Unknown history type") 103 | } 104 | 105 | status, err := z.request("history.get", params, result) 106 | if err != nil { 107 | return nil, status, err 108 | } 109 | 110 | return result, status, nil 111 | } 112 | -------------------------------------------------------------------------------- /history_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | const ( 8 | testHistoryItemID = 45503 9 | testHistoryType = 0 10 | ) 11 | 12 | func TestHistoryCRUD(t *testing.T) { 13 | 14 | var z Context 15 | 16 | // Login 17 | loginTest(&z, t) 18 | defer logoutTest(&z, t) 19 | 20 | // Get 21 | testHistoryGet(t, z) 22 | } 23 | 24 | func testHistoryGet(t *testing.T, z Context) []HistoryFloatObject { 25 | 26 | r := []HistoryFloatObject{} 27 | 28 | hObjects, _, err := z.HistoryGet(HistoryGetParams{ 29 | History: HistoryObjectTypeFloat, 30 | //ItemIDs: []int{testHistoryItemID}, 31 | GetParameters: GetParameters{ 32 | Limit: 1, 33 | }, 34 | }) 35 | 36 | if err != nil { 37 | t.Error("History get error:", err) 38 | } else { 39 | r = *hObjects.(*[]HistoryFloatObject) 40 | if len(r) == 0 { 41 | t.Error("History get error: unable to find history") 42 | } else { 43 | t.Logf("History get: success") 44 | } 45 | } 46 | 47 | return r 48 | } 49 | -------------------------------------------------------------------------------- /host.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `HostObject` field: `Available` 4 | const ( 5 | HostAvailableUnknown = 0 6 | HostAvailableAvailable = 1 7 | HostAvailableUnavailable = 2 8 | ) 9 | 10 | // For `HostObject` field: `Flags` 11 | const ( 12 | HostFlagsPlain = 0 13 | HostFlagsDiscovered = 4 14 | ) 15 | 16 | // For `HostObject` field: `Flags` 17 | const ( 18 | HostInventoryModeDisabled = -1 19 | HostInventoryModeManual = 0 20 | HostInventoryModeAutomatic = 1 21 | ) 22 | 23 | // For `HostObject` field: `IpmiAuthtype` 24 | const ( 25 | HostIpmiAuthtypeDefault = -1 26 | HostIpmiAuthtypeNone = 0 27 | HostIpmiAuthtypeMD2 = 1 28 | HostIpmiAuthtypeMD5 = 2 29 | HostIpmiAuthtypeStraight = 4 30 | HostIpmiAuthtypeOEM = 5 31 | HostIpmiAuthtypeRMCP = 6 32 | ) 33 | 34 | // For `HostObject` field: `IpmiAvailable` 35 | const ( 36 | HostIpmiAvailableUnknown = 0 37 | HostIpmiAvailableAvailable = 1 38 | HostIpmiAvailableUnavailable = 2 39 | ) 40 | 41 | // For `HostObject` field: `IpmiPrivilege` 42 | const ( 43 | HostIpmiPrivilegeCallback = 1 44 | HostIpmiPrivilegeUser = 2 45 | HostIpmiPrivilegeOperator = 3 46 | HostIpmiPrivilegeAdmin = 4 47 | HostIpmiPrivilegeOEM = 5 48 | ) 49 | 50 | // For `HostObject` field: `JmxAvailable` 51 | const ( 52 | HostJmxAvailableUnknown = 0 53 | HostJmxAvailableAvailable = 1 54 | HostJmxAvailableUnavailable = 2 55 | ) 56 | 57 | // For `HostObject` field: `MaintenanceStatus` 58 | const ( 59 | HostMaintenanceStatusDisable = 0 60 | HostMaintenanceStatusEnable = 1 61 | ) 62 | 63 | // For `HostObject` field: `MaintenanceType` 64 | const ( 65 | HostMaintenanceTypeDataCollectionEnabled = 0 66 | HostMaintenanceTypeDataCollectionDisabled = 1 67 | ) 68 | 69 | // For `HostObject` field: `SnmpAvailable` 70 | const ( 71 | HostSnmpAvailableUnknown = 0 72 | HostSnmpAvailableAvailable = 1 73 | HostSnmpAvailableUnavailable = 2 74 | ) 75 | 76 | // For `HostObject` field: `Status` 77 | const ( 78 | HostStatusMonitored = 0 79 | HostStatusUnmonitored = 1 80 | ) 81 | 82 | // For `HostObject` field: `TLSConnect` 83 | const ( 84 | TLSConnectNoEncryption = 1 85 | TLSConnectPSK = 2 86 | TLSConnectCertificate = 4 87 | ) 88 | 89 | // For `HostObject` field: `TLSAccept` 90 | const ( 91 | TLSAcceptNoEncryption = 1 92 | TLSAcceptPSK = 2 93 | TLSAcceptCertificate = 4 94 | ) 95 | 96 | // For `HostGetParams` field: `Evaltype` 97 | const ( 98 | HostEvaltypeAndOr = 0 99 | HostEvaltypeOr = 2 100 | ) 101 | 102 | // For `HostTag` field: `Operator` 103 | const ( 104 | HostTagOperatorContains = 0 105 | HostTagOperatorEquals = 1 106 | ) 107 | 108 | // HostObject struct is used to store host operations results 109 | // 110 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/host/object#host 111 | type HostObject struct { 112 | HostID int `json:"hostid,omitempty"` 113 | Host string `json:"host,omitempty"` 114 | Available int `json:"available,omitempty"` // has defined consts, see above 115 | Description string `json:"description,omitempty"` 116 | DisableUntil int `json:"disable_until,omitempty"` 117 | Error string `json:"error,omitempty"` 118 | ErrorsFrom int `json:"errors_from,omitempty"` 119 | Flags int `json:"flags,omitempty"` // has defined consts, see above 120 | InventoryMode int `json:"inventory_mode,omitempty"` // has defined consts, see above 121 | IpmiAuthtype int `json:"ipmi_authtype,omitempty"` // has defined consts, see above 122 | IpmiAvailable int `json:"ipmi_available,omitempty"` // has defined consts, see above 123 | IpmiDisableUntil int `json:"ipmi_disable_until,omitempty"` 124 | IpmiError string `json:"ipmi_error,omitempty"` 125 | IpmiErrorsFrom int `json:"ipmi_errors_from,omitempty"` 126 | IpmiPassword string `json:"ipmi_password,omitempty"` 127 | IpmiPrivilege int `json:"ipmi_privilege,omitempty"` // has defined consts, see above 128 | IpmiUsername string `json:"ipmi_username,omitempty"` 129 | JmxAvailable int `json:"jmx_available,omitempty"` // has defined consts, see above 130 | JmxDisableUntil int `json:"jmx_disable_until,omitempty"` 131 | JmxError string `json:"jmx_error,omitempty"` 132 | JmxErrorsFrom int `json:"jmx_errors_from,omitempty"` 133 | MaintenanceFrom int `json:"maintenance_from,omitempty"` 134 | MaintenanceStatus int `json:"maintenance_status,omitempty"` // has defined consts, see above 135 | MaintenanceType int `json:"maintenance_type,omitempty"` // has defined consts, see above 136 | MaintenanceID int `json:"maintenanceid,omitempty"` 137 | Name string `json:"name,omitempty"` 138 | ProxyHostID int `json:"proxy_hostid,omitempty"` 139 | SnmpAvailable int `json:"snmp_available,omitempty"` // has defined consts, see above 140 | SnmpDisableUntil int `json:"snmp_disable_until,omitempty"` 141 | SnmpError string `json:"snmp_error,omitempty"` 142 | SnmpErrorsFrom int `json:"snmp_errors_from,omitempty"` 143 | Status int `json:"status,omitempty"` // has defined consts, see above 144 | TLSConnect int `json:"tls_connect,omitempty"` // has defined consts, see above 145 | TLSAccept int `json:"tls_accept,omitempty"` // has defined consts, see above 146 | TLSIssuer string `json:"tls_issuer,omitempty"` 147 | TLSSubject string `json:"tls_subject,omitempty"` 148 | TLSPSKIdentity string `json:"tls_psk_identity,omitempty"` 149 | TLSPSK string `json:"tls_psk,omitempty"` 150 | 151 | Groups []HostgroupObject `json:"groups,omitempty"` 152 | Interfaces []HostinterfaceObject `json:"interfaces,omitempty"` 153 | Tags []HostTagObject `json:"tags,omitempty"` 154 | InheritedTags []HostTagObject `json:"inheritedTags,omitempty"` 155 | Macros []UsermacroObject `json:"macros,omitempty"` 156 | Templates []TemplateObject `json:"templates,omitempty"` // Used for `create` operations 157 | ParentTemplates []TemplateObject `json:"parentTemplates,omitempty"` // Used to store result for `get` operations 158 | } 159 | 160 | // HostTagObject struct is used to store host tag 161 | // 162 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/host/object#host_tag 163 | type HostTagObject struct { 164 | Tag string `json:"tag"` 165 | Value string `json:"value,omitempty"` 166 | 167 | Operator int `json:"operator,omitempty"` // Used for `get` operations, has defined consts, see above 168 | } 169 | 170 | // HostGetParams struct is used for host get requests 171 | // 172 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/host/get#parameters 173 | type HostGetParams struct { 174 | GetParameters 175 | 176 | GroupIDs []int `json:"groupids,omitempty"` 177 | ApplicationIDs []int `json:"applicationids,omitempty"` 178 | DserviceIDs []int `json:"dserviceids,omitempty"` 179 | GraphIDs []int `json:"graphids,omitempty"` 180 | HostIDs []int `json:"hostids,omitempty"` 181 | HttptestIDs []int `json:"httptestids,omitempty"` 182 | InterfaceIDs []int `json:"interfaceids,omitempty"` 183 | ItemIDs []int `json:"itemids,omitempty"` 184 | MaintenanceIDs []int `json:"maintenanceids,omitempty"` 185 | MonitoredHosts bool `json:"monitored_hosts,omitempty"` 186 | ProxyHosts bool `json:"proxy_hosts,omitempty"` 187 | ProxyIDs []int `json:"proxyids,omitempty"` 188 | TemplatedHosts bool `json:"templated_hosts,omitempty"` 189 | TemplateIDs []int `json:"templateids,omitempty"` 190 | TriggerIDs []int `json:"triggerids,omitempty"` 191 | 192 | WithItems bool `json:"with_items,omitempty"` 193 | WithItemPrototypes bool `json:"with_item_prototypes,omitempty"` 194 | WithSimpleGraphItemPrototypes bool `json:"with_simple_graph_item_prototypes,omitempty"` 195 | WithApplications bool `json:"with_applications,omitempty"` 196 | WithGraphs bool `json:"with_graphs,omitempty"` 197 | WithGraphPrototypes bool `json:"with_graph_prototypes,omitempty"` 198 | WithHttptests bool `json:"with_httptests,omitempty"` 199 | WithMonitoredHttptests bool `json:"with_monitored_httptests,omitempty"` 200 | WithMonitoredItems bool `json:"with_monitored_items,omitempty"` 201 | WithMonitoredTriggers bool `json:"with_monitored_triggers,omitempty"` 202 | WithSimpleGraphItems bool `json:"with_simple_graph_items,omitempty"` 203 | WithTriggers bool `json:"with_triggers,omitempty"` 204 | WithProblemsSuppressed bool `json:"withProblemsSuppressed,omitempty"` 205 | Evaltype int `json:"evaltype,omitempty"` // has defined consts, see above 206 | Severities []int `json:"severities,omitempty"` 207 | Tags []HostTagObject `json:"tags,omitempty"` 208 | InheritedTags bool `json:"inheritedTags,omitempty"` 209 | 210 | // SelectApplications SelectQuery `json:"selectApplications,omitempty"` // not implemented yet 211 | // SelectDiscoveries SelectQuery `json:"selectDiscoveries,omitempty"` // not implemented yet 212 | // SelectDiscoveryRule SelectQuery `json:"selectDiscoveryRule ,omitempty"` // not implemented yet 213 | // SelectGraphs SelectQuery `json:"selectGraphs,omitempty"` // not implemented yet 214 | SelectGroups SelectQuery `json:"selectGroups,omitempty"` 215 | // SelectHostDiscovery SelectQuery `json:"selectHostDiscovery ,omitempty"` // not implemented yet 216 | // SelectHTTPTests SelectQuery `json:"selectHttpTests,omitempty"` // not implemented yet 217 | SelectInterfaces SelectQuery `json:"selectInterfaces,omitempty"` 218 | // SelectInventory SelectQuery `json:"selectInventory,omitempty"` // not implemented yet 219 | // SelectItems SelectQuery `json:"selectItems,omitempty"` // not implemented yet 220 | SelectMacros SelectQuery `json:"selectMacros,omitempty"` 221 | SelectParentTemplates SelectQuery `json:"selectParentTemplates,omitempty"` 222 | // SelectScreens SelectQuery `json:"selectScreens,omitempty"` // not implemented yet 223 | SelectTags SelectQuery `json:"selectTags,omitempty"` 224 | SelectInheritedTags SelectQuery `json:"selectInheritedTags,omitempty"` 225 | // SelectTriggers SelectQuery `json:"selectTriggers,omitempty"` // not implemented yet 226 | } 227 | 228 | // Structure to store creation result 229 | type hostCreateResult struct { 230 | HostIDs []int `json:"hostids"` 231 | } 232 | 233 | // Structure to store updation result 234 | type hostUpdateResult struct { 235 | HostIDs []int `json:"hostids"` 236 | } 237 | 238 | // Structure to store deletion result 239 | type hostDeleteResult struct { 240 | HostIDs []int `json:"hostids"` 241 | } 242 | 243 | // HostGet gets hosts 244 | func (z *Context) HostGet(params HostGetParams) ([]HostObject, int, error) { 245 | 246 | var result []HostObject 247 | 248 | status, err := z.request("host.get", params, &result) 249 | if err != nil { 250 | return nil, status, err 251 | } 252 | 253 | return result, status, nil 254 | } 255 | 256 | // HostCreate creates hosts 257 | func (z *Context) HostCreate(params []HostObject) ([]int, int, error) { 258 | 259 | var result hostCreateResult 260 | 261 | status, err := z.request("host.create", params, &result) 262 | if err != nil { 263 | return nil, status, err 264 | } 265 | 266 | return result.HostIDs, status, nil 267 | } 268 | 269 | // HostUpdate updates hosts 270 | func (z *Context) HostUpdate(params []HostObject) ([]int, int, error) { 271 | 272 | var result hostUpdateResult 273 | 274 | status, err := z.request("host.update", params, &result) 275 | if err != nil { 276 | return nil, status, err 277 | } 278 | 279 | return result.HostIDs, status, nil 280 | } 281 | 282 | // HostDelete deletes hosts 283 | func (z *Context) HostDelete(hostIDs []int) ([]int, int, error) { 284 | 285 | var result hostDeleteResult 286 | 287 | status, err := z.request("host.delete", hostIDs, &result) 288 | if err != nil { 289 | return nil, status, err 290 | } 291 | 292 | return result.HostIDs, status, nil 293 | } 294 | -------------------------------------------------------------------------------- /host_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testHostName = "testHost" 10 | testHostIP = "10.1.1.1" 11 | testHostPort = "10150" 12 | testMacro = "{$TEST_MACRO}" 13 | testMacroValue = "testMacroValue" 14 | ) 15 | 16 | func TestHostCRUD(t *testing.T) { 17 | 18 | var z Context 19 | 20 | // Login 21 | loginTest(&z, t) 22 | defer logoutTest(&z, t) 23 | 24 | // Preparing auxiliary data 25 | hgCreatedIDs := testHostgroupCreate(t, z) 26 | defer testHostgroupDelete(t, z, hgCreatedIDs) 27 | 28 | tCreatedIDs := testTemplateCreate(t, z, hgCreatedIDs) 29 | defer testTemplateDelete(t, z, tCreatedIDs) 30 | 31 | // Create and delete 32 | hCreatedIDs := testHostCreate(t, z, hgCreatedIDs, tCreatedIDs) 33 | defer testHostDelete(t, z, hCreatedIDs) 34 | 35 | // Update 36 | testHostUpdate(t, z, hCreatedIDs) 37 | 38 | // Get 39 | testHostGet(t, z, hCreatedIDs, tCreatedIDs, hgCreatedIDs) 40 | } 41 | 42 | func testHostCreate(t *testing.T, z Context, hgCreatedIDs, tCreatedIDs []int) []int { 43 | 44 | var groups []HostgroupObject 45 | var templates []TemplateObject 46 | 47 | // Add groups to host 48 | for _, e := range hgCreatedIDs { 49 | groups = append(groups, HostgroupObject{ 50 | GroupID: e, 51 | }) 52 | } 53 | 54 | // Add templates to host 55 | for _, e := range tCreatedIDs { 56 | templates = append(templates, TemplateObject{ 57 | TemplateID: e, 58 | }) 59 | } 60 | 61 | hCreatedIDs, _, err := z.HostCreate([]HostObject{ 62 | { 63 | Host: testHostName, 64 | Groups: groups, 65 | Templates: templates, 66 | Interfaces: []HostinterfaceObject{ 67 | { 68 | IP: testHostIP, 69 | Main: HostinterfaceMainDefault, 70 | Port: testHostPort, 71 | Type: HostinterfaceTypeAgent, 72 | UseIP: HostinterfaceUseipIP, 73 | }, 74 | }, 75 | Macros: []UsermacroObject{ 76 | { 77 | Macro: testMacro, 78 | Value: testMacroValue, 79 | }, 80 | }, 81 | }, 82 | }) 83 | 84 | if err != nil { 85 | t.Fatal("Host create error:", err) 86 | } 87 | 88 | if len(hCreatedIDs) == 0 { 89 | t.Fatal("Host create error: empty IDs array") 90 | } 91 | 92 | t.Logf("Host create: success") 93 | 94 | return hCreatedIDs 95 | } 96 | 97 | func testHostUpdate(t *testing.T, z Context, hCreatedIDs []int) []int { 98 | 99 | var hObjects []HostObject 100 | 101 | // Preparing host objects array to update 102 | for _, i := range hCreatedIDs { 103 | hObjects = append(hObjects, HostObject{ 104 | HostID: i, 105 | Name: testHostName + "_upd", 106 | }) 107 | } 108 | 109 | hUpdatedIDs, _, err := z.HostUpdate(hObjects) 110 | if err != nil { 111 | t.Fatal("Host update error:", err) 112 | } 113 | 114 | if len(hUpdatedIDs) == 0 { 115 | t.Fatal("Host update error: empty IDs array") 116 | } 117 | 118 | if reflect.DeepEqual(hUpdatedIDs, hCreatedIDs) == false { 119 | t.Fatal("Host update error: IDs arrays for created and updated hosts are mismatch") 120 | } 121 | 122 | t.Logf("Host update: success") 123 | 124 | return hUpdatedIDs 125 | } 126 | 127 | func testHostDelete(t *testing.T, z Context, hCreatedIDs []int) []int { 128 | 129 | hDeletedIDs, _, err := z.HostDelete(hCreatedIDs) 130 | if err != nil { 131 | t.Fatal("Host delete error:", err) 132 | } 133 | 134 | if len(hDeletedIDs) == 0 { 135 | t.Fatal("Host delete error: empty IDs array") 136 | } 137 | 138 | if reflect.DeepEqual(hDeletedIDs, hCreatedIDs) == false { 139 | t.Fatal("Host delete error: IDs arrays for created and deleted host are mismatch") 140 | } 141 | 142 | t.Logf("Host delete: success") 143 | 144 | return hDeletedIDs 145 | } 146 | 147 | func testHostGet(t *testing.T, z Context, hCreatedIDs, tCreatedIDs, hgCreatedIDs []int) []HostObject { 148 | 149 | hObjects, _, err := z.HostGet(HostGetParams{ 150 | SelectParentTemplates: SelectExtendedOutput, 151 | SelectMacros: SelectExtendedOutput, 152 | HostIDs: hCreatedIDs, 153 | TemplateIDs: tCreatedIDs, 154 | GroupIDs: hgCreatedIDs, 155 | GetParameters: GetParameters{ 156 | Filter: map[string]interface{}{ 157 | "name": testHostName + "_upd", 158 | }, 159 | Output: SelectExtendedOutput, 160 | }, 161 | }) 162 | 163 | if err != nil { 164 | t.Error("Host get error:", err) 165 | } else { 166 | if len(hObjects) == 0 { 167 | t.Error("Host get error: unable to find created host") 168 | } else { 169 | 170 | // Check macro in each created host 171 | for _, h := range hObjects { 172 | 173 | foundMacro := false 174 | 175 | for _, m := range h.Macros { 176 | if m.Macro == testMacro && m.Value == testMacroValue { 177 | foundMacro = true 178 | break 179 | } 180 | } 181 | 182 | if foundMacro == false { 183 | t.Error("Host get error: unable to find macro in created host") 184 | } 185 | } 186 | 187 | t.Logf("Host get: success") 188 | } 189 | } 190 | 191 | return hObjects 192 | } 193 | -------------------------------------------------------------------------------- /hostgroup.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `HostgroupObject` field: `Status` 4 | const ( 5 | HostgroupFlagsPlain = 0 6 | HostgroupFlagsDiscrovered = 4 7 | ) 8 | 9 | // For `HostgroupObject` field: `Internal` 10 | const ( 11 | HostgroupInternalFalse = 0 12 | HostgroupInternalTrue = 1 13 | ) 14 | 15 | // HostgroupObject struct is used to store hostgroup operations results 16 | // 17 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/object 18 | type HostgroupObject struct { 19 | GroupID int `json:"groupid,omitempty"` 20 | Name string `json:"name,omitempty"` 21 | Flags int `json:"flags,omitempty"` // has defined consts, see above 22 | Internal int `json:"internal,omitempty"` // has defined consts, see above 23 | 24 | Hosts []HostObject `json:"hosts,omitempty"` 25 | Templates []TemplateObject `json:"templates,omitempty"` 26 | } 27 | 28 | // HostgroupGetParams struct is used for hostgroup get requests 29 | // 30 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/hostgroup/get#parameters 31 | type HostgroupGetParams struct { 32 | GetParameters 33 | 34 | GraphIDs []int `json:"graphids,omitempty"` 35 | GroupIDs []int `json:"groupids,omitempty"` 36 | HostIDs []int `json:"hostids,omitempty"` 37 | MaintenanceIDs []int `json:"maintenanceids,omitempty"` 38 | MonitoredHosts bool `json:"monitored_hosts,omitempty"` 39 | RealHosts bool `json:"real_hosts,omitempty"` 40 | TemplatedHosts bool `json:"templated_hosts,omitempty"` 41 | TemplateIDs []int `json:"templateids,omitempty"` 42 | TriggerIDs []int `json:"triggerids,omitempty"` 43 | 44 | WithApplications bool `json:"with_applications,omitempty"` 45 | WithGraphs bool `json:"with_graphs,omitempty"` 46 | WithGraphPrototypes bool `json:"with_graph_prototypes,omitempty"` 47 | WithHostsAndTemplates bool `json:"with_hosts_and_templates,omitempty"` 48 | WithHttptests bool `json:"with_httptests,omitempty"` 49 | WithItems bool `json:"with_items,omitempty"` 50 | WithItemPrototypes bool `json:"with_item_prototypes,omitempty"` 51 | WithSimpleGraphItemPrototypes bool `json:"with_simple_graph_item_prototypes,omitempty"` 52 | WithMonitoredHttptests bool `json:"with_monitored_httptests,omitempty"` 53 | WithMonitoredItems bool `json:"with_monitored_items,omitempty"` 54 | WithMonitoredTriggers bool `json:"with_monitored_triggers,omitempty"` 55 | WithSimpleGraphItems bool `json:"with_simple_graph_items,omitempty"` 56 | WithTriggers bool `json:"with_triggers,omitempty"` 57 | 58 | // SelectDiscoveryRule SelectQuery `json:"selectDiscoveryRule,omitempty"` // not implemented yet 59 | // SelectGroupDiscovery SelectQuery `json:"selectGroupDiscovery,omitempty"` // not implemented yet 60 | SelectHosts SelectQuery `json:"selectHosts,omitempty"` 61 | SelectTemplates SelectQuery `json:"selectTemplates,omitempty"` 62 | } 63 | 64 | // Structure to store creation result 65 | type hostgroupCreateResult struct { 66 | GroupIDs []int `json:"groupids"` 67 | } 68 | 69 | // Structure to store deletion result 70 | type hostgroupDeleteResult struct { 71 | GroupIDs []int `json:"groupids"` 72 | } 73 | 74 | // HostgroupGet gets hostgroups 75 | func (z *Context) HostgroupGet(params HostgroupGetParams) ([]HostgroupObject, int, error) { 76 | 77 | var result []HostgroupObject 78 | 79 | status, err := z.request("hostgroup.get", params, &result) 80 | if err != nil { 81 | return nil, status, err 82 | } 83 | 84 | return result, status, nil 85 | } 86 | 87 | // HostgroupCreate creates hostgroups 88 | func (z *Context) HostgroupCreate(params []HostgroupObject) ([]int, int, error) { 89 | 90 | var result hostgroupCreateResult 91 | 92 | status, err := z.request("hostgroup.create", params, &result) 93 | if err != nil { 94 | return nil, status, err 95 | } 96 | 97 | return result.GroupIDs, status, nil 98 | } 99 | 100 | // HostgroupDelete deletes hostgroups 101 | func (z *Context) HostgroupDelete(groupIDs []int) ([]int, int, error) { 102 | 103 | var result hostgroupDeleteResult 104 | 105 | status, err := z.request("hostgroup.delete", groupIDs, &result) 106 | if err != nil { 107 | return nil, status, err 108 | } 109 | 110 | return result.GroupIDs, status, nil 111 | } 112 | -------------------------------------------------------------------------------- /hostgroup_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testHostgroupName = "testHostgroup" 10 | ) 11 | 12 | func TestHostgroupCRUD(t *testing.T) { 13 | 14 | var z Context 15 | 16 | // Login 17 | loginTest(&z, t) 18 | defer logoutTest(&z, t) 19 | 20 | // Create and delete 21 | hgCreatedIDs := testHostgroupCreate(t, z) 22 | defer testHostgroupDelete(t, z, hgCreatedIDs) 23 | 24 | // Get 25 | testHostgroupGet(t, z, hgCreatedIDs) 26 | } 27 | 28 | func testHostgroupCreate(t *testing.T, z Context) []int { 29 | 30 | hgCreatedIDs, _, err := z.HostgroupCreate([]HostgroupObject{ 31 | { 32 | Name: testHostgroupName, 33 | }, 34 | }) 35 | if err != nil { 36 | t.Fatal("Hostgroup create error:", err) 37 | } 38 | 39 | if len(hgCreatedIDs) == 0 { 40 | t.Fatal("Hostgroup create error: empty IDs array") 41 | } 42 | 43 | t.Logf("Hostgroup create: success") 44 | 45 | return hgCreatedIDs 46 | } 47 | 48 | func testHostgroupDelete(t *testing.T, z Context, hgCreatedIDs []int) []int { 49 | 50 | hgDeletedIDs, _, err := z.HostgroupDelete(hgCreatedIDs) 51 | if err != nil { 52 | t.Fatal("Hostgroup delete error:", err) 53 | } 54 | 55 | if len(hgDeletedIDs) == 0 { 56 | t.Fatal("Hostgroup delete error: empty IDs array") 57 | } 58 | 59 | if reflect.DeepEqual(hgDeletedIDs, hgCreatedIDs) == false { 60 | t.Fatal("Hostgroup delete error: IDs arrays for created and deleted hostgroup are mismatch") 61 | } 62 | 63 | t.Logf("Hostgroup delete: success") 64 | 65 | return hgDeletedIDs 66 | } 67 | 68 | func testHostgroupGet(t *testing.T, z Context, hgCreatedIDs []int) []HostgroupObject { 69 | 70 | hgObjects, _, err := z.HostgroupGet(HostgroupGetParams{ 71 | GroupIDs: hgCreatedIDs, 72 | GetParameters: GetParameters{ 73 | Filter: map[string]interface{}{ 74 | "name": testHostgroupName, 75 | }, 76 | Output: SelectExtendedOutput, 77 | }, 78 | }) 79 | 80 | if err != nil { 81 | t.Error("Hostgroup get error:", err) 82 | } else { 83 | if len(hgObjects) == 0 { 84 | t.Error("Hostgroup get error: unable to find created hostgroup") 85 | } else { 86 | t.Logf("Hostgroup get: success") 87 | } 88 | } 89 | 90 | return hgObjects 91 | } 92 | -------------------------------------------------------------------------------- /hostinterface.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `HostinterfaceObject` field: `Main` 4 | const ( 5 | HostinterfaceMainNotDefault = 0 6 | HostinterfaceMainDefault = 1 7 | ) 8 | 9 | // For `HostinterfaceObject` field: `Type` 10 | const ( 11 | HostinterfaceTypeAgent = 1 12 | HostinterfaceTypeSNMP = 2 13 | HostinterfaceTypeIPMI = 3 14 | HostinterfaceTypeJMX = 4 15 | ) 16 | 17 | // For `HostinterfaceObject` field: `UseIP` 18 | const ( 19 | HostinterfaceUseipDNS = 0 20 | HostinterfaceUseipIP = 1 21 | ) 22 | 23 | // For `HostinterfaceDetailsTagObject` field: `Bulk` 24 | const ( 25 | HostinterfaceDetailsTagBulkDontUse = 0 26 | HostinterfaceDetailsTagBulkUse = 1 27 | ) 28 | 29 | // For `HostinterfaceDetailsTagObject` field: `Version` 30 | const ( 31 | HostinterfaceDetailsTagVersionSNMPv1 = 1 32 | HostinterfaceDetailsTagVersionSNMPv2c = 2 33 | HostinterfaceDetailsTagVersionSNMPv3 = 3 34 | ) 35 | 36 | // For `HostinterfaceDetailsTagObject` field: `SecurityLevel` 37 | const ( 38 | HostinterfaceDetailsTagSecurityLevelNoAuthNoPriv = 0 39 | HostinterfaceDetailsTagSecurityLevelAuthNoPriv = 1 40 | HostinterfaceDetailsTagSecurityLevelAuthPriv = 2 41 | ) 42 | 43 | // For `HostinterfaceDetailsTagObject` field: `AuthProtocol` 44 | const ( 45 | HostinterfaceDetailsTagAuthProtocolMD5 = 0 46 | HostinterfaceDetailsTagAuthProtocolSHA = 1 47 | ) 48 | 49 | // For `HostinterfaceDetailsTagObject` field: `PrivProtocol` 50 | const ( 51 | HostinterfaceDetailsTagPrivProtocolDES = 0 52 | HostinterfaceDetailsTagPrivProtocolAES = 1 53 | ) 54 | 55 | // HostinterfaceObject struct is used to store hostinterface operations results 56 | // 57 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/hostinterface/object#hostinterface 58 | type HostinterfaceObject struct { 59 | InterfaceID int `json:"interfaceid,omitempty"` 60 | DNS string `json:"dns"` 61 | HostID int `json:"hostid,omitempty"` 62 | IP string `json:"ip"` 63 | Main int `json:"main"` // has defined consts, see above 64 | Port string `json:"port"` 65 | Type int `json:"type"` // has defined consts, see above 66 | UseIP int `json:"useip"` // has defined consts, see above 67 | Details []HostinterfaceDetailsTagObject `json:"details,omitempty"` 68 | 69 | // Items []ItemObject `json:"items,omitempty"` // not implemented yet 70 | Hosts []HostObject `json:"hosts,omitempty"` 71 | } 72 | 73 | // HostinterfaceDetailsTagObject struct is used to store hostinterface details 74 | // 75 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/hostinterface/object#details_tag 76 | type HostinterfaceDetailsTagObject struct { 77 | Version int `json:"version,omitempty"` // has defined consts, see above 78 | Bulk int `json:"bulk,omitempty"` // has defined consts, see above 79 | Community string `json:"community,omitempty"` 80 | SecurityName string `json:"securityname,omitempty"` 81 | SecurityLevel int `json:"securitylevel,omitempty"` // has defined consts, see above 82 | AuthPassPhrase string `json:"authpassphrase,omitempty"` 83 | PrivPassPhrase string `json:"privpassphrase,omitempty"` 84 | AuthProtocol int `json:"authprotocol,omitempty"` // has defined consts, see above 85 | PrivProtocol int `json:"privprotocol,omitempty"` // has defined consts, see above 86 | ContextName string `json:"contextname,omitempty"` 87 | } 88 | 89 | // HostinterfaceGetParams struct is used for hostinterface get requests 90 | // 91 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/hostinterface/get#parameters 92 | type HostinterfaceGetParams struct { 93 | GetParameters 94 | 95 | HostIDs []int `json:"hostids,omitempty"` 96 | InterfaceIDs []int `json:"interfaceids,omitempty"` 97 | ItemIDs []int `json:"itemids,omitempty"` 98 | TriggerIDs []int `json:"triggerids,omitempty"` 99 | 100 | // SelectItems SelectQuery `json:"selectItems,omitempty"` // not implemented yet 101 | SelectHosts SelectQuery `json:"selectHosts,omitempty"` 102 | } 103 | 104 | // Structure to store creation result 105 | type hostinterfaceCreateResult struct { 106 | InterfaceIDs []int `json:"interfaceids"` 107 | } 108 | 109 | // Structure to store deletion result 110 | type hostinterfaceDeleteResult struct { 111 | InterfaceIDs []int `json:"interfaceids"` 112 | } 113 | 114 | // HostinterfaceGet gets hostinterfaces 115 | func (z *Context) HostinterfaceGet(params HostinterfaceGetParams) ([]HostinterfaceObject, int, error) { 116 | 117 | var result []HostinterfaceObject 118 | 119 | status, err := z.request("hostinterface.get", params, &result) 120 | if err != nil { 121 | return nil, status, err 122 | } 123 | 124 | return result, status, nil 125 | } 126 | 127 | // HostinterfaceCreate creates hostinterfaces 128 | func (z *Context) HostinterfaceCreate(params []HostinterfaceObject) ([]int, int, error) { 129 | 130 | var result hostinterfaceCreateResult 131 | 132 | status, err := z.request("hostinterface.create", params, &result) 133 | if err != nil { 134 | return nil, status, err 135 | } 136 | 137 | return result.InterfaceIDs, status, nil 138 | } 139 | 140 | // HostinterfaceDelete deletes hostinterfaces 141 | func (z *Context) HostinterfaceDelete(hostinterfaceIDs []int) ([]int, int, error) { 142 | 143 | var result hostinterfaceDeleteResult 144 | 145 | status, err := z.request("hostinterface.delete", hostinterfaceIDs, &result) 146 | if err != nil { 147 | return nil, status, err 148 | } 149 | 150 | return result.InterfaceIDs, status, nil 151 | } 152 | -------------------------------------------------------------------------------- /hostinterface_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testHostinterfaceIP = "10.1.1.2" 10 | testHostinterfacePort = "10151" 11 | ) 12 | 13 | func TestHostinterfaceCRUD(t *testing.T) { 14 | 15 | var z Context 16 | 17 | // Login 18 | loginTest(&z, t) 19 | defer logoutTest(&z, t) 20 | 21 | // Preparing auxiliary data 22 | hgCreatedIDs := testHostgroupCreate(t, z) 23 | defer testHostgroupDelete(t, z, hgCreatedIDs) 24 | 25 | tCreatedIDs := testTemplateCreate(t, z, hgCreatedIDs) 26 | defer testTemplateDelete(t, z, tCreatedIDs) 27 | 28 | hCreatedIDs := testHostCreate(t, z, hgCreatedIDs, tCreatedIDs) 29 | defer testHostDelete(t, z, hCreatedIDs) 30 | 31 | // Create and delete 32 | hiCreatedIDs := testHostinterfaceCreate(t, z, hCreatedIDs[0]) 33 | defer testHostinterfaceDelete(t, z, hiCreatedIDs) 34 | 35 | // Get 36 | testHostinterfaceGet(t, z, hCreatedIDs) 37 | } 38 | 39 | func testHostinterfaceCreate(t *testing.T, z Context, hCreatedID int) []int { 40 | 41 | hiCreatedIDs, _, err := z.HostinterfaceCreate([]HostinterfaceObject{ 42 | { 43 | HostID: hCreatedID, 44 | IP: testHostinterfaceIP, 45 | Main: HostinterfaceMainNotDefault, 46 | Port: testHostinterfacePort, 47 | Type: HostinterfaceTypeAgent, 48 | UseIP: HostinterfaceUseipIP, 49 | }, 50 | }) 51 | 52 | if err != nil { 53 | t.Fatal("Hostinterface create error:", err) 54 | } 55 | 56 | if len(hiCreatedIDs) == 0 { 57 | t.Fatal("Hostinterface create error: empty IDs array") 58 | } 59 | 60 | t.Logf("Hostinterface create: success") 61 | 62 | return hiCreatedIDs 63 | } 64 | 65 | func testHostinterfaceDelete(t *testing.T, z Context, hiCreatedIDs []int) []int { 66 | 67 | hiDeletedIDs, _, err := z.HostinterfaceDelete(hiCreatedIDs) 68 | if err != nil { 69 | t.Fatal("Hostinterface delete error:", err) 70 | } 71 | 72 | if len(hiDeletedIDs) == 0 { 73 | t.Fatal("Hostinterface delete error: empty IDs array") 74 | } 75 | 76 | if reflect.DeepEqual(hiDeletedIDs, hiCreatedIDs) == false { 77 | t.Fatal("Hostinterface delete error: IDs arrays for created and deleted hostinterface are mismatch") 78 | } 79 | 80 | t.Logf("Hostinterface delete: success") 81 | 82 | return hiDeletedIDs 83 | } 84 | 85 | func testHostinterfaceGet(t *testing.T, z Context, hCreatedIDs []int) []HostinterfaceObject { 86 | 87 | hiObjects, _, err := z.HostinterfaceGet(HostinterfaceGetParams{ 88 | SelectHosts: SelectExtendedOutput, 89 | HostIDs: hCreatedIDs, 90 | GetParameters: GetParameters{ 91 | Filter: map[string]interface{}{ 92 | "ip": testHostinterfaceIP, 93 | }, 94 | Output: SelectExtendedOutput, 95 | }, 96 | }) 97 | 98 | if err != nil { 99 | t.Error("Hostinterface get error:", err) 100 | } else { 101 | if len(hiObjects) == 0 { 102 | t.Error("Hostinterface get error: unable to find created hostinterface") 103 | } else { 104 | t.Logf("Hostinterface get: success") 105 | } 106 | } 107 | 108 | return hiObjects 109 | } 110 | -------------------------------------------------------------------------------- /mediatype.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `MediatypeObject` field: `Type` 4 | const ( 5 | MediatypeEmail = 0 6 | MediatypeScript = 1 7 | MediatypeSMS = 2 8 | MediatypeWebhook = 4 9 | ) 10 | 11 | // For `MediatypeObject` field: `SMTPSecurity` 12 | const ( 13 | MediatypeSMTPSecurityNone = 0 14 | MediatypeSMTPSecuritySTARTTLS = 1 15 | MediatypeSMTPSecuritySSLTLS = 2 16 | ) 17 | 18 | // For `MediatypeObject` field: `SMTPVerifyHost` 19 | const ( 20 | MediatypeSMTPVerifyHostNo = 0 21 | MediatypeSMTPVerifyHostYes = 1 22 | ) 23 | 24 | // For `MediatypeObject` field: `SMTPVerifyPeer` 25 | const ( 26 | MediatypeSMTPVerifyPeerNo = 0 27 | MediatypeSMTPVerifyPeerYes = 1 28 | ) 29 | 30 | // For `MediatypeObject` field: `SMTPAuthentication` 31 | const ( 32 | MediatypeSMTPAuthenticationNone = 0 33 | MediatypeSMTPAuthenticationNormalPassword = 1 34 | ) 35 | 36 | // For `MediatypeObject` field: `Status` 37 | const ( 38 | MediatypeStatusEnabled = 0 39 | MediatypeScriptDisabled = 1 40 | ) 41 | 42 | // For `MediatypeObject` field: `ContentType` 43 | const ( 44 | MediatypeContentTypePlainText = 0 45 | MediatypeContentTypeHTML = 1 46 | ) 47 | 48 | // For `MediatypeObject` field: `ProcessTags` 49 | const ( 50 | MediatypeProcessTagsNo = 0 51 | MediatypeProcessTagsYes = 1 52 | ) 53 | 54 | // For `MediatypeObject` field: `ShowEventMenu` 55 | const ( 56 | MediatypeShowEventMenuNo = 0 57 | MediatypeShowEventMenuYes = 1 58 | ) 59 | 60 | // For `MediatypeMessageTemplateObject` field: `EventSource` 61 | const ( 62 | MediatypeMessageTemplateEventSourceTriggers = 0 63 | MediatypeMessageTemplateEventSourceDiscovery = 1 64 | MediatypeMessageTemplateEventSourceAutoregistration = 2 65 | MediatypeMessageTemplateEventSourceInternal = 3 66 | ) 67 | 68 | // For `MediatypeMessageTemplateObject` field: `Recovery` 69 | const ( 70 | MediatypeMessageTemplateRecoveryOperations = 0 71 | MediatypeMessageTemplateRecoveryRecoveryOperations = 1 72 | MediatypeMessageTemplateRecoveryUpdateOperations = 2 73 | ) 74 | 75 | // MediatypeObject struct is used to store mediatype operations results 76 | // 77 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/mediatype/object 78 | type MediatypeObject struct { 79 | MediatypeID int `json:"mediatypeid,omitempty"` 80 | Name string `json:"name,omitempty"` 81 | Type int `json:"type,omitempty"` // has defined consts, see above 82 | ExecPath string `json:"exec_path,omitempty"` 83 | GsmModem string `json:"gsm_modem,omitempty"` 84 | Passwd string `json:"passwd,omitempty"` 85 | SMTPEmail string `json:"smtp_email,omitempty"` 86 | SMTPHelo string `json:"smtp_helo,omitempty"` 87 | SMTPServer string `json:"smtp_server,omitempty"` 88 | SMTPPort int `json:"smtp_port,omitempty"` 89 | SMTPSecurity int `json:"smtp_security,omitempty"` // has defined consts, see above 90 | SMTPVerifyHost int `json:"smtp_verify_host,omitempty"` // has defined consts, see above 91 | SMTPVerifyPeer int `json:"smtp_verify_peer,omitempty"` // has defined consts, see above 92 | SMTPAuthentication int `json:"smtp_authentication,omitempty"` // has defined consts, see above 93 | Status int `json:"status,omitempty"` // has defined consts, see above 94 | Username string `json:"username,omitempty"` 95 | ExecParams string `json:"exec_params,omitempty"` 96 | MaxSessions int `json:"maxsessions,omitempty"` 97 | MaxAttempts int `json:"maxattempts,omitempty"` 98 | AttemptInterval string `json:"attempt_interval,omitempty"` 99 | ContentType int `json:"content_type,omitempty"` // has defined consts, see above 100 | Script string `json:"script,omitempty"` 101 | Timeout string `json:"timeout,omitempty"` 102 | ProcessTags int `json:"process_tags,omitempty"` // has defined consts, see above 103 | ShowEventMenu int `json:"show_event_menu,omitempty"` // has defined consts, see above 104 | EventMenuURL string `json:"event_menu_url,omitempty"` 105 | EventMenuName string `json:"event_menu_name,omitempty"` 106 | Parameters []MediatypeWebhookParametersObject `json:"parameters,omitempty"` 107 | Description string `json:"description,omitempty"` 108 | MessageTemplates []MediatypeMessageTemplateObject `json:"message_templates,omitempty"` 109 | 110 | Users []UserObject `json:"users,omitempty"` 111 | } 112 | 113 | // MediatypeWebhookParametersObject struct is used for mediatypes webhook parameters 114 | // 115 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/mediatype/object#webhook_parameters 116 | type MediatypeWebhookParametersObject struct { 117 | Name string `json:"name,omitempty"` 118 | Value string `json:"value,omitempty"` 119 | } 120 | 121 | // MediatypeMessageTemplateObject struct is used for mediatypes message template 122 | // 123 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/mediatype/object#message_template 124 | type MediatypeMessageTemplateObject struct { 125 | EventSource int `json:"eventsource"` // has defined consts, see above 126 | Recovery int `json:"recovery"` // has defined consts, see above 127 | Subject string `json:"subject,omitempty"` 128 | Message string `json:"message,omitempty"` 129 | } 130 | 131 | // MediatypeGetParams struct is used for mediatype get requests 132 | // 133 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/mediatype/get#parameters 134 | type MediatypeGetParams struct { 135 | GetParameters 136 | 137 | MediatypeIDs []int `json:"mediatypeids,omitempty"` 138 | MediaIDs []int `json:"mediaids,omitempty"` 139 | UserIDs []int `json:"userids,omitempty"` 140 | 141 | SelectMessageTemplates SelectQuery `json:"selectMessageTemplates,omitempty"` 142 | SelectUsers SelectQuery `json:"selectUsers,omitempty"` 143 | } 144 | 145 | // Structure to store creation result 146 | type mediatypeCreateResult struct { 147 | MediatypeIDs []int `json:"mediatypeids"` 148 | } 149 | 150 | // Structure to store deletion result 151 | type mediatypeDeleteResult struct { 152 | MediatypeIDs []int `json:"mediatypeids"` 153 | } 154 | 155 | // MediatypeGet gets mediatypes 156 | func (z *Context) MediatypeGet(params MediatypeGetParams) ([]MediatypeObject, int, error) { 157 | 158 | var result []MediatypeObject 159 | 160 | status, err := z.request("mediatype.get", params, &result) 161 | if err != nil { 162 | return nil, status, err 163 | } 164 | 165 | return result, status, nil 166 | } 167 | 168 | // MediatypeCreate creates mediatypes 169 | func (z *Context) MediatypeCreate(params []MediatypeObject) ([]int, int, error) { 170 | 171 | var result mediatypeCreateResult 172 | 173 | status, err := z.request("mediatype.create", params, &result) 174 | if err != nil { 175 | return nil, status, err 176 | } 177 | 178 | return result.MediatypeIDs, status, nil 179 | } 180 | 181 | // MediatypeDelete deletes mediatypes 182 | func (z *Context) MediatypeDelete(mediatypeIDs []int) ([]int, int, error) { 183 | 184 | var result mediatypeDeleteResult 185 | 186 | status, err := z.request("mediatype.delete", mediatypeIDs, &result) 187 | if err != nil { 188 | return nil, status, err 189 | } 190 | 191 | return result.MediatypeIDs, status, nil 192 | } 193 | -------------------------------------------------------------------------------- /mediatype_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testMediatypeName = "testMediatypeName" 10 | testMediatypeDescription = "testMediatypeDescription" 11 | testMediatypeExecPath = "test_script.sh" 12 | ) 13 | 14 | func TestMediatypeCRUD(t *testing.T) { 15 | 16 | var z Context 17 | 18 | // Login 19 | loginTest(&z, t) 20 | defer logoutTest(&z, t) 21 | 22 | // Create and delete 23 | mtCreatedIDs := testMediatypeCreate(t, z) 24 | defer testMediatypeDelete(t, z, mtCreatedIDs) 25 | 26 | // Get 27 | testMediatypeGet(t, z, mtCreatedIDs) 28 | } 29 | 30 | func testMediatypeCreate(t *testing.T, z Context) []int { 31 | 32 | hiCreatedIDs, _, err := z.MediatypeCreate([]MediatypeObject{ 33 | { 34 | Name: testMediatypeName, 35 | Description: testMediatypeDescription, 36 | Type: MediatypeScript, 37 | ExecPath: testMediatypeExecPath, 38 | MessageTemplates: []MediatypeMessageTemplateObject{ 39 | { 40 | EventSource: MediatypeMessageTemplateEventSourceTriggers, 41 | Recovery: MediatypeMessageTemplateRecoveryOperations, 42 | Subject: "SSS", 43 | Message: "MMM", 44 | }, 45 | }, 46 | }, 47 | }) 48 | 49 | if err != nil { 50 | t.Fatal("Mediatype create error:", err) 51 | } 52 | 53 | if len(hiCreatedIDs) == 0 { 54 | t.Fatal("Mediatype create error: empty IDs array") 55 | } 56 | 57 | t.Logf("Mediatype create: success") 58 | 59 | return hiCreatedIDs 60 | } 61 | 62 | func testMediatypeDelete(t *testing.T, z Context, mtCreatedIDs []int) []int { 63 | 64 | mtDeletedIDs, _, err := z.MediatypeDelete(mtCreatedIDs) 65 | if err != nil { 66 | t.Fatal("Mediatype delete error:", err) 67 | } 68 | 69 | if len(mtDeletedIDs) == 0 { 70 | t.Fatal("Mediatype delete error: empty IDs array") 71 | } 72 | 73 | if reflect.DeepEqual(mtDeletedIDs, mtCreatedIDs) == false { 74 | t.Fatal("Mediatype delete error: IDs arrays for created and deleted mediatype are mismatch") 75 | } 76 | 77 | t.Logf("Mediatype delete: success") 78 | 79 | return mtDeletedIDs 80 | } 81 | 82 | func testMediatypeGet(t *testing.T, z Context, mtCreatedIDs []int) []MediatypeObject { 83 | 84 | mtObjects, _, err := z.MediatypeGet(MediatypeGetParams{ 85 | SelectUsers: SelectExtendedOutput, 86 | MediatypeIDs: mtCreatedIDs, 87 | GetParameters: GetParameters{ 88 | Filter: map[string]interface{}{ 89 | "name": testMediatypeName, 90 | "exec_path": testMediatypeExecPath, 91 | }, 92 | Output: SelectExtendedOutput, 93 | }, 94 | }) 95 | 96 | if err != nil { 97 | t.Error("Mediatype get error:", err) 98 | } else { 99 | if len(mtObjects) == 0 { 100 | t.Error("Mediatype get error: unable to find created mediatype") 101 | } else { 102 | t.Logf("Mediatype get: success") 103 | } 104 | } 105 | 106 | return mtObjects 107 | } 108 | -------------------------------------------------------------------------------- /problem.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | type ProblemSourceType int64 4 | 5 | const ( 6 | ProblemSourceTypeTrigger ProblemSourceType = 0 7 | ProblemSourceTypeInternal ProblemSourceType = 3 8 | ProblemSourceTypeServiceStatusUpdate ProblemSourceType = 4 9 | ) 10 | 11 | type ProblemObjectType int64 12 | 13 | const ( 14 | ProblemObjectTypeTrigger ProblemObjectType = 0 15 | ProblemObjectTypeItem ProblemObjectType = 4 16 | ProblemObjectTypeLLDRule ProblemObjectType = 5 17 | ProblemObjectTypeService ProblemObjectType = 6 18 | ) 19 | 20 | type ProblemAcknowledgeType int64 21 | 22 | const ( 23 | ProblemAcknowledgeTypeFalse ProblemAcknowledgeType = 0 24 | ProblemAcknowledgeTypeTrue ProblemAcknowledgeType = 1 25 | ) 26 | 27 | type ProblemSeverityType int64 28 | 29 | const ( 30 | ProblemSeverityTypeNotClassified ProblemSeverityType = 0 31 | ProblemSeverityTypeInformation ProblemSeverityType = 1 32 | ProblemSeverityTypeWarning ProblemSeverityType = 2 33 | ProblemSeverityTypeAverage ProblemSeverityType = 3 34 | ProblemSeverityTypeHigh ProblemSeverityType = 4 35 | ProblemSeverityTypeDisaster ProblemSeverityType = 5 36 | ) 37 | 38 | type ProblemSuppressedType int64 39 | 40 | const ( 41 | ProblemSuppressedTypeNormalState ProblemSuppressedType = 0 42 | ProblemSuppressedTypeSuppressed ProblemSuppressedType = 1 43 | ) 44 | 45 | type ProblemEvalType int64 46 | 47 | const ( 48 | ProblemEvalTypeAndOr ProblemEvalType = 0 49 | ProblemEvalTypeOR ProblemEvalType = 2 50 | ) 51 | 52 | // ProblemObject struct is used to store problem operations results 53 | // 54 | // see: https://www.zabbix.com/documentation/5.0/en/manual/api/reference/problem/object 55 | type ProblemObject struct { 56 | EventID int64 `json:"eventid,omitempty"` 57 | Source ProblemSourceType `json:"source,omitempty"` 58 | Object ProblemObjectType `json:"object,omitempty"` 59 | ObjectID int64 `json:"objectid,omitempty"` 60 | Clock int64 `json:"clock,omitempty"` 61 | Ns int64 `json:"ns,omitempty"` 62 | REventID int64 `json:"r_eventid,omitempty"` 63 | RClock int64 `json:"r_clock,omitempty"` 64 | RNs int64 `json:"r_ns,omitempty"` 65 | CauseEventID int64 `json:"cause_eventid,omitempty"` 66 | CorrelationID int64 `json:"correlationid,omitempty"` 67 | UserID int64 `json:"userid,omitempty"` 68 | Name string `json:"name,omitempty"` 69 | Acknowledged ProblemAcknowledgeType `json:"acknowledged,omitempty"` 70 | Severity ProblemSeverityType `json:"severity,omitempty"` 71 | Suppressed ProblemSuppressedType `json:"suppressed,omitempty"` 72 | OpData string `json:"opdata,omitempty"` 73 | URLs []ProblemMediaTypeURLObject `json:"urls,omitempty"` 74 | Acknowledges []ProblemAcknowledgeObject `json:"acknowledges,omitempty"` 75 | Tags []ProblemTagObject `json:"tags,omitempty"` 76 | Suppression []ProblemSuppressionObject `json:"suppression_data,omitempty"` 77 | } 78 | 79 | type ProblemAcknowledgeObject struct { 80 | AcknowledgeID int64 `json:"acknowledgeid,omitempty"` 81 | UserID int64 `json:"userid,omitempty"` 82 | EventID int64 `json:"eventid,omitempty"` 83 | Clock int64 `json:"clock,omitempty"` 84 | Message string `json:"message,omitempty"` 85 | Action EventAcknowledgeActionType `json:"action,omitempty"` 86 | OldSeverity ProblemSeverityType `json:"old_severity,omitempty"` 87 | NewSeverity ProblemSeverityType `json:"new_severity,omitempty"` 88 | SuppressUntil int64 `json:"suppress_until,omitempty"` 89 | TaskID int64 `json:"taskid,omitempty"` 90 | } 91 | 92 | type ProblemMediaTypeURLObject struct { 93 | Name string `json:"name,omitempty"` 94 | URL string `json:"url,omitempty"` 95 | } 96 | 97 | type ProblemTagObject struct { 98 | Tag string `json:"tag,omitempty"` 99 | Value string `json:"value,omitempty"` 100 | } 101 | 102 | type ProblemSuppressionObject struct { 103 | MaintenanceID int64 `json:"maintenanceid,omitempty"` 104 | UserID int64 `json:"userid,omitempty"` 105 | SuppressUntil int64 `json:"suppress_until,omitempty"` 106 | } 107 | 108 | // ProblemGetParams struct is used for problem get requests 109 | // 110 | // see: https://www.zabbix.com/documentation/5.0/en/manual/api/reference/problem/get#parameters 111 | type ProblemGetParams struct { 112 | GetParameters 113 | 114 | EventIDs []int64 `json:"eventids,omitempty"` 115 | GroupIDs []int64 `json:"groupids,omitempty"` 116 | HostIDs []int64 `json:"hostids,omitempty"` 117 | ObjectIDs []int64 `json:"objectids,omitempty"` 118 | ApplicationIDs []int64 `json:"applicationids,omitempty"` 119 | Source ProblemSourceType `json:"source,omitempty"` 120 | Object ProblemObjectType `json:"object,omitempty"` 121 | Acknowledged bool `json:"acknowledged,omitempty"` 122 | Suppressed bool `json:"suppressed,omitempty"` 123 | Severities []ProblemSeverityType `json:"severities,omitempty"` 124 | Evaltype ProblemEvalType `json:"evaltype,omitempty"` 125 | Tags []ProblemTagObject `json:"tags,omitempty"` 126 | Recent bool `json:"recent,omitempty"` 127 | EventIDFrom int64 `json:"eventid_from,omitempty"` 128 | EventIDTill int64 `json:"eventid_till,omitempty"` 129 | TimeFrom int64 `json:"time_from,omitempty"` 130 | TimeTill int64 `json:"time_till,omitempty"` 131 | SelectAcknowledges SelectQuery `json:"selectAcknowledges,omitempty"` 132 | SelectTags SelectQuery `json:"selectTags,omitempty"` 133 | SelectSuppressionData SelectQuery `json:"selectSuppressionData,omitempty"` 134 | SortField []string `json:"sortfield,omitempty"` 135 | } 136 | 137 | // ProblemGet gets problems 138 | func (z *Context) ProblemGet(params ProblemGetParams) ([]ProblemObject, int, error) { 139 | 140 | var result []ProblemObject 141 | 142 | status, err := z.request("problem.get", params, &result) 143 | if err != nil { 144 | return nil, status, err 145 | } 146 | 147 | return result, status, nil 148 | } 149 | -------------------------------------------------------------------------------- /problem_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestProblemCRUD(t *testing.T) { 8 | 9 | var z Context 10 | 11 | // Login 12 | loginTest(&z, t) 13 | defer logoutTest(&z, t) 14 | 15 | // Get 16 | testProblemGet(t, z) 17 | } 18 | 19 | func testProblemGet(t *testing.T, z Context) { 20 | 21 | pObjects, _, err := z.ProblemGet(ProblemGetParams{ 22 | //ObjectIDs: []int{20143}, 23 | // ... Add other fields as needed 24 | }) 25 | 26 | if err != nil { 27 | t.Error("Problem get error:", err) 28 | } else { 29 | if len(pObjects) == 0 { 30 | t.Error("Problem get error: unable to find problems") 31 | } else { 32 | t.Logf("Problem get: success") 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /template.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `TemplateGetParams` field: `Evaltype` 4 | const ( 5 | TemplateEvaltypeAndOr = 0 6 | TemplateEvaltypeOr = 2 7 | ) 8 | 9 | // For `TemplateTag` field: `Operator` 10 | const ( 11 | TemplateTagOperatorContains = 0 12 | TemplateTagOperatorEquals = 1 13 | ) 14 | 15 | // TemplateObject struct is used to store template operations results 16 | // 17 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/template/object 18 | type TemplateObject struct { 19 | TemplateID int `json:"templateid,omitempty"` 20 | Host string `json:"host,omitempty"` 21 | Description string `json:"description,omitempty"` 22 | Name string `json:"name,omitempty"` 23 | 24 | Groups []HostgroupObject `json:"groups,omitempty"` 25 | Tags []TemplateTagObject `json:"tags,omitempty"` 26 | Templates []TemplateObject `json:"templates,omitempty"` 27 | ParentTemplates []TemplateObject `json:"parentTemplates,omitempty"` 28 | Macros []UsermacroObject `json:"macros,omitempty"` 29 | Hosts []HostObject `json:"hosts,omitempty"` 30 | } 31 | 32 | // TemplateTagObject struct is used to store template tag data 33 | // 34 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/template/object#template_tag 35 | type TemplateTagObject struct { 36 | Tag string `json:"tag,omitempty"` 37 | Value string `json:"value,omitempty"` 38 | 39 | Operator int `json:"operator,omitempty"` // Used for `get` operations, has defined consts, see above 40 | } 41 | 42 | // TemplateGetParams struct is used for template get requests 43 | // 44 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/template/get#parameters 45 | type TemplateGetParams struct { 46 | GetParameters 47 | 48 | TemplateIDs []int `json:"templateids,omitempty"` 49 | GroupIDs []int `json:"groupids,omitempty"` 50 | ParentTemplateIDs []int `json:"parentTemplateids,omitempty"` 51 | HostIDs []int `json:"hostids,omitempty"` 52 | GraphIDs []int `json:"graphids,omitempty"` 53 | ItemIDs []int `json:"itemids,omitempty"` 54 | TriggerIDs []int `json:"triggerids,omitempty"` 55 | 56 | WithItems bool `json:"with_items,omitempty"` 57 | WithTriggers bool `json:"with_triggers,omitempty"` 58 | WithGraphs bool `json:"with_graphs,omitempty"` 59 | WithHttptests bool `json:"with_httptests,omitempty"` 60 | Evaltype int `json:"evaltype,omitempty"` // has defined consts, see above 61 | Tags []TemplateTagObject `json:"tags,omitempty"` 62 | 63 | SelectGroups SelectQuery `json:"selectGroups,omitempty"` 64 | SelectTags SelectQuery `json:"selectTags,omitempty"` 65 | SelectHosts SelectQuery `json:"selectHosts,omitempty"` 66 | SelectTemplates SelectQuery `json:"selectTemplates,omitempty"` 67 | SelectParentTemplates SelectQuery `json:"selectParentTemplates,omitempty"` 68 | SelectMacros SelectQuery `json:"selectMacros,omitempty"` 69 | 70 | // SelectHttpTests SelectQuery `json:"selectHttpTests,omitempty"` // not implemented yet 71 | // SelectItems SelectQuery `json:"selectItems,omitempty"` // not implemented yet 72 | // SelectDiscoveries SelectQuery `json:"selectDiscoveries,omitempty"` // not implemented yet 73 | // SelectTriggers SelectQuery `json:"selectTriggers,omitempty"` // not implemented yet 74 | // SelectGraphs SelectQuery `json:"selectGraphs,omitempty"` // not implemented yet 75 | // SelectApplications SelectQuery `json:"selectApplications,omitempty"` // not implemented yet 76 | // SelectScreens SelectQuery `json:"selectScreens,omitempty"` // not implemented yet 77 | } 78 | 79 | // Structure to store creation result 80 | type templateCreateResult struct { 81 | TemplateIDs []int `json:"templateids"` 82 | } 83 | 84 | // Structure to store deletion result 85 | type templateDeleteResult struct { 86 | TemplateIDs []int `json:"templateids"` 87 | } 88 | 89 | // TemplateGet gets templates 90 | func (z *Context) TemplateGet(params TemplateGetParams) ([]TemplateObject, int, error) { 91 | 92 | var result []TemplateObject 93 | 94 | status, err := z.request("template.get", params, &result) 95 | if err != nil { 96 | return nil, status, err 97 | } 98 | 99 | return result, status, nil 100 | } 101 | 102 | // TemplateCreate creates templates 103 | func (z *Context) TemplateCreate(params []TemplateObject) ([]int, int, error) { 104 | 105 | var result templateCreateResult 106 | 107 | status, err := z.request("template.create", params, &result) 108 | if err != nil { 109 | return nil, status, err 110 | } 111 | 112 | return result.TemplateIDs, status, nil 113 | } 114 | 115 | // TemplateDelete deletes templates 116 | func (z *Context) TemplateDelete(templateIDs []int) ([]int, int, error) { 117 | 118 | var result templateDeleteResult 119 | 120 | status, err := z.request("template.delete", templateIDs, &result) 121 | if err != nil { 122 | return nil, status, err 123 | } 124 | 125 | return result.TemplateIDs, status, nil 126 | } 127 | -------------------------------------------------------------------------------- /template_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testTemplateName = "testTemplate" 10 | ) 11 | 12 | func TestTemplateCRUD(t *testing.T) { 13 | 14 | var z Context 15 | 16 | // Login 17 | loginTest(&z, t) 18 | defer logoutTest(&z, t) 19 | 20 | // Preparing auxiliary data 21 | hgCreatedIDs := testHostgroupCreate(t, z) 22 | defer testHostgroupDelete(t, z, hgCreatedIDs) 23 | 24 | // Create and delete 25 | tCreatedIDs := testTemplateCreate(t, z, hgCreatedIDs) 26 | defer testTemplateDelete(t, z, tCreatedIDs) 27 | 28 | // Get 29 | testTemplateGet(t, z, tCreatedIDs, hgCreatedIDs) 30 | } 31 | 32 | func testTemplateCreate(t *testing.T, z Context, hgCreatedIDs []int) []int { 33 | 34 | var groups []HostgroupObject 35 | 36 | // Add groups to template 37 | for _, e := range hgCreatedIDs { 38 | groups = append(groups, HostgroupObject{ 39 | GroupID: e, 40 | }) 41 | } 42 | 43 | tCreatedIDs, _, err := z.TemplateCreate([]TemplateObject{ 44 | { 45 | Host: testTemplateName, 46 | Groups: groups, 47 | }, 48 | }) 49 | if err != nil { 50 | t.Fatal("Template create error:", err) 51 | } 52 | 53 | if len(tCreatedIDs) == 0 { 54 | t.Fatal("Template create error: empty IDs array") 55 | } 56 | 57 | t.Logf("Template create: success") 58 | 59 | return tCreatedIDs 60 | } 61 | 62 | func testTemplateDelete(t *testing.T, z Context, tCreatedIDs []int) []int { 63 | 64 | tDeletedIDs, _, err := z.TemplateDelete(tCreatedIDs) 65 | if err != nil { 66 | t.Fatal("Template delete error:", err) 67 | } 68 | 69 | if len(tDeletedIDs) == 0 { 70 | t.Fatal("Template delete error: empty IDs array") 71 | } 72 | 73 | if reflect.DeepEqual(tDeletedIDs, tCreatedIDs) == false { 74 | t.Fatal("Template delete error: IDs arrays for created and deleted template are mismatch") 75 | } 76 | 77 | t.Logf("Template delete: success") 78 | 79 | return tDeletedIDs 80 | } 81 | 82 | func testTemplateGet(t *testing.T, z Context, tCreatedIDs, hgCreatedIDs []int) []TemplateObject { 83 | 84 | tObjects, _, err := z.TemplateGet(TemplateGetParams{ 85 | TemplateIDs: tCreatedIDs, 86 | GroupIDs: hgCreatedIDs, 87 | GetParameters: GetParameters{ 88 | Filter: map[string]interface{}{ 89 | "name": testTemplateName, 90 | }, 91 | Output: SelectExtendedOutput, 92 | }, 93 | }) 94 | 95 | if err != nil { 96 | t.Error("Template get error:", err) 97 | } else { 98 | if len(tObjects) == 0 { 99 | t.Error("Template get error: unable to find created template") 100 | } else { 101 | t.Logf("Template get: success") 102 | } 103 | } 104 | 105 | return tObjects 106 | } 107 | -------------------------------------------------------------------------------- /user.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `UserObject` field: `AutoLogin` 4 | const ( 5 | UserAutoLoginDisabled = 0 6 | UserAutoLoginEnabled = 1 7 | ) 8 | 9 | // For `UserObject` field: `Theme` 10 | const ( 11 | UserThemeDefault = "default" 12 | UserThemeBlue = "blue-theme" 13 | UserThemeDark = "dark-theme" 14 | ) 15 | 16 | // For `UserObject` field: `Type` 17 | const ( 18 | UserTypeUser = 1 19 | UserTypeAdmin = 2 20 | UserTypeSuperAdmin = 3 21 | ) 22 | 23 | // For `MediaObject` field: `Active` 24 | const ( 25 | MediaActiveEnabled = 0 26 | MediaActiveDisabled = 1 27 | ) 28 | 29 | // UserObject struct is used to store user operations results 30 | // 31 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/user/object 32 | type UserObject struct { 33 | UserID int `json:"userid,omitempty"` 34 | Alias string `json:"alias,omitempty"` 35 | AttemptClock int `json:"attempt_clock,omitempty"` 36 | AttemptFailed int `json:"attempt_failed,omitempty"` 37 | AttemptIP string `json:"attempt_ip,omitempty"` 38 | AutoLogin int `json:"autologin,omitempty"` // has defined consts, see above 39 | AutoLogout string `json:"autologout"` 40 | Lang string `json:"lang,omitempty"` 41 | Name string `json:"name,omitempty"` 42 | Refresh string `json:"refresh,omitempty"` 43 | RowsPerPage int `json:"rows_per_page,omitempty"` 44 | Surname string `json:"surname,omitempty"` 45 | Theme string `json:"theme,omitempty"` // has defined consts, see above 46 | Type int `json:"type,omitempty"` // has defined consts, see above 47 | URL string `json:"url,omitempty"` 48 | 49 | // used for user.login 50 | UserDataObject 51 | 52 | Medias []MediaObject `json:"medias,omitempty"` 53 | Mediatypes []MediatypeObject `json:"mediatypes,omitempty"` 54 | Usrgrps []UsergroupObject `json:"usrgrps,omitempty"` 55 | 56 | // used when new user created 57 | UserMedias []MediaObject `json:"user_medias,omitempty"` 58 | Passwd string `json:"passwd,omitempty"` 59 | } 60 | 61 | // MediaObject struct is used to store media operations results 62 | // 63 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/user/object#media 64 | type MediaObject struct { 65 | MediaID int `json:"mediaid,omitempty"` 66 | MediaTypeID int `json:"mediatypeid,omitempty"` 67 | SendTo []string `json:"sendto,omitempty"` 68 | Active int `json:"active,omitempty"` // has defined consts, see above 69 | Severity int `json:"severity,omitempty"` 70 | Period string `json:"period,omitempty"` 71 | } 72 | 73 | // UserLoginParams struct is used for login requests 74 | // 75 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/user/login#parameters 76 | type UserLoginParams struct { 77 | User string `json:"user"` 78 | Password string `json:"password"` 79 | UserData string `json:"userData,omitempty"` 80 | } 81 | 82 | // UserDataObject struct is used to store authenticated user additional info 83 | // 84 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/user/login#return_values 85 | type UserDataObject struct { 86 | DebugMode bool `json:"debug_mode,omitempty"` 87 | GUIAccess int `json:"gui_access,omitempty"` 88 | SessionID string `json:"sessionid,omitempty"` 89 | UserIP string `json:"userip,omitempty"` 90 | } 91 | 92 | // UserGetParams struct is used for user get requests 93 | // 94 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/user/get#parameters 95 | type UserGetParams struct { 96 | GetParameters 97 | 98 | MediaIDs []int `json:"mediaids,omitempty"` 99 | NediatypeIDs []int `json:"mediatypeids,omitempty"` 100 | UserIDs []int `json:"userids,omitempty"` 101 | UsrgrpIDs []int `json:"usrgrpids,omitempty"` 102 | 103 | GetAccess bool `json:"getAccess,omitempty"` 104 | SelectMedias SelectQuery `json:"selectMedias,omitempty"` 105 | SelectMediatypes SelectQuery `json:"selectMediatypes,omitempty"` 106 | SelectUsrgrps SelectQuery `json:"selectUsrgrps,omitempty"` 107 | } 108 | 109 | // Structure to store creation result 110 | type userCreateResult struct { 111 | UserIDs []int `json:"userids"` 112 | } 113 | 114 | // Structure to store deletion result 115 | type userDeleteResult struct { 116 | UserIDs []int `json:"userids"` 117 | } 118 | 119 | // UserGet gets users 120 | func (z *Context) UserGet(params UserGetParams) ([]UserObject, int, error) { 121 | 122 | var result []UserObject 123 | 124 | status, err := z.request("user.get", params, &result) 125 | if err != nil { 126 | return nil, status, err 127 | } 128 | 129 | return result, status, nil 130 | } 131 | 132 | // UserCreate creates users 133 | func (z *Context) UserCreate(params []UserObject) ([]int, int, error) { 134 | 135 | var result userCreateResult 136 | 137 | status, err := z.request("user.create", params, &result) 138 | if err != nil { 139 | return nil, status, err 140 | } 141 | 142 | return result.UserIDs, status, nil 143 | } 144 | 145 | // UserDelete deletes users 146 | func (z *Context) UserDelete(userIDs []int) ([]int, int, error) { 147 | 148 | var result userDeleteResult 149 | 150 | status, err := z.request("user.delete", userIDs, &result) 151 | if err != nil { 152 | return nil, status, err 153 | } 154 | 155 | return result.UserIDs, status, nil 156 | } 157 | 158 | func (z *Context) userLogin(params UserLoginParams) (string, int, error) { 159 | 160 | var result string 161 | 162 | status, err := z.request("user.login", params, &result) 163 | if err != nil { 164 | return "", status, err 165 | } 166 | 167 | return result, status, nil 168 | } 169 | 170 | func (z *Context) userLogout() (bool, int, error) { 171 | 172 | var result bool 173 | 174 | status, err := z.request("user.logout", []string{}, &result) 175 | if err != nil { 176 | return false, status, err 177 | } 178 | 179 | return result, status, nil 180 | } 181 | -------------------------------------------------------------------------------- /user_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testUserAlias = "testUserAlias" 10 | testUserName = "testUserName" 11 | testUserSurname = "testUserSurname" 12 | testUserPasswd = "testUserPasswd" 13 | testUserLang = "ru_RU" 14 | testUserMediaEmail = "test_user@domain.com" 15 | testUserMediaSeverity = 63 16 | testUserMediaPeriod = "1-7,00:00-24:00" 17 | ) 18 | 19 | func TestUserCRUD(t *testing.T) { 20 | 21 | var z Context 22 | 23 | // Login 24 | loginTest(&z, t) 25 | defer logoutTest(&z, t) 26 | 27 | // Preparing auxiliary data 28 | ugCreatedIDs := testUsergroupCreate(t, z) 29 | defer testUsergroupDelete(t, z, ugCreatedIDs) 30 | 31 | // Create and delete 32 | uCreatedIDs := testUserCreate(t, z, ugCreatedIDs) 33 | defer testUserDelete(t, z, uCreatedIDs) 34 | 35 | // Get 36 | testUserGet(t, z, uCreatedIDs) 37 | } 38 | 39 | func testUserCreate(t *testing.T, z Context, ugCreatedIDs []int) []int { 40 | 41 | var usergroups []UsergroupObject 42 | 43 | // Add usergroups to user 44 | for _, e := range ugCreatedIDs { 45 | usergroups = append(usergroups, UsergroupObject{ 46 | UsrgrpID: e, 47 | }) 48 | } 49 | 50 | uCreatedIDs, _, err := z.UserCreate([]UserObject{ 51 | { 52 | Alias: testUserAlias, 53 | Name: testUserName, 54 | Surname: testUserSurname, 55 | Passwd: testUserPasswd, 56 | AutoLogin: UserAutoLoginDisabled, 57 | AutoLogout: "15m", 58 | Lang: testUserLang, 59 | Type: UserTypeUser, 60 | Refresh: "90s", 61 | Usrgrps: usergroups, 62 | UserMedias: []MediaObject{ 63 | { 64 | MediaTypeID: 1, 65 | SendTo: []string{testUserMediaEmail}, 66 | Active: MediaActiveEnabled, 67 | Severity: testUserMediaSeverity, 68 | Period: testUserMediaPeriod, 69 | }, 70 | }, 71 | }, 72 | }) 73 | if err != nil { 74 | t.Fatal("User create error:", err) 75 | } 76 | 77 | if len(uCreatedIDs) == 0 { 78 | t.Fatal("User create error: empty IDs array") 79 | } 80 | 81 | t.Logf("User create: success") 82 | 83 | return uCreatedIDs 84 | } 85 | 86 | func testUserDelete(t *testing.T, z Context, uCreatedIDs []int) []int { 87 | 88 | uDeletedIDs, _, err := z.UserDelete(uCreatedIDs) 89 | if err != nil { 90 | t.Fatal("User delete error:", err) 91 | } 92 | 93 | if len(uDeletedIDs) == 0 { 94 | t.Fatal("User delete error: empty IDs array") 95 | } 96 | 97 | if reflect.DeepEqual(uDeletedIDs, uCreatedIDs) == false { 98 | t.Fatal("User delete error: IDs arrays for created and deleted user are mismatch") 99 | } 100 | 101 | t.Logf("User delete: success") 102 | 103 | return uDeletedIDs 104 | } 105 | 106 | func testUserGet(t *testing.T, z Context, uCreatedIDs []int) []UserObject { 107 | 108 | uObjects, _, err := z.UserGet(UserGetParams{ 109 | UserIDs: uCreatedIDs, 110 | SelectMedias: SelectExtendedOutput, 111 | SelectMediatypes: SelectExtendedOutput, 112 | SelectUsrgrps: SelectExtendedOutput, 113 | GetParameters: GetParameters{ 114 | Filter: map[string]interface{}{ 115 | "alias": testUserAlias, 116 | "name": testUserName, 117 | "surname": testUserSurname, 118 | }, 119 | Output: SelectExtendedOutput, 120 | }, 121 | }) 122 | 123 | if err != nil { 124 | t.Error("User get error:", err) 125 | } else { 126 | if len(uObjects) == 0 { 127 | t.Error("User get error: unable to find created user") 128 | } else { 129 | t.Logf("User get: success") 130 | } 131 | } 132 | 133 | return uObjects 134 | } 135 | -------------------------------------------------------------------------------- /usergroup.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `UsergroupObject` field: `DebugMode` 4 | const ( 5 | UsergroupDebugModeDisabled = 0 6 | UsergroupDebugModeEnabled = 1 7 | ) 8 | 9 | // For `UsergroupObject` field: `GuiAccess` 10 | const ( 11 | UsergroupGuiAccessSystemDefaultAuth = 0 12 | UsergroupGuiAccessInternalAuth = 1 13 | UsergroupGuiAccessLDAPAuth = 2 14 | UsergroupGuiAccessDisableFrontend = 3 15 | ) 16 | 17 | // For `UsergroupObject` field: `UsersStatus` 18 | const ( 19 | UsergroupUsersStatusEnabled = 0 20 | UsergroupUsersStatusDisabled = 1 21 | ) 22 | 23 | // For `UsergroupPermissionObject` field: `Permission` 24 | const ( 25 | UsergroupPermissionDenied = 0 26 | UsergroupPermissionRO = 2 27 | UsergroupPermissionRW = 3 28 | ) 29 | 30 | // UsergroupObject struct is used to store usergroup operations results 31 | // 32 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/usergroup/object#user_group 33 | type UsergroupObject struct { 34 | UsrgrpID int `json:"usrgrpid,omitempty"` 35 | Name string `json:"name,omitempty"` 36 | DebugMode int `json:"debug_mode,omitempty"` // has defined consts, see above 37 | GuiAccess int `json:"gui_access,omitempty"` // has defined consts, see above 38 | UsersStatus int `json:"users_status,omitempty"` // has defined consts, see above 39 | 40 | Users []UserObject `json:"users,omitempty"` 41 | Rights []UsergroupPermissionObject `json:"rights,omitempty"` 42 | TagFilters []UsergroupTagBasedPermissionObject `json:"tag_filters,omitempty"` 43 | 44 | // used when new usergroup created or updated 45 | UserIDs []int `json:"userids,omitempty"` 46 | } 47 | 48 | // UsergroupPermissionObject struct is used to store usergroup permissions 49 | // 50 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/usergroup/object#permission 51 | type UsergroupPermissionObject struct { 52 | ID int `json:"id"` 53 | Permission int `json:"permission"` // has defined consts, see above 54 | } 55 | 56 | // UsergroupTagBasedPermissionObject struct is used to store usergroup tag based permission 57 | // 58 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/usergroup/object#tag_based_permission 59 | type UsergroupTagBasedPermissionObject struct { 60 | GroupID int `json:"groupid,omitempty"` 61 | Tag string `json:"tag,omitempty"` 62 | Value string `json:"value,omitempty"` 63 | } 64 | 65 | // UsergroupGetParams struct is used for usergroup get requests 66 | // 67 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/usergroup/get#parameters 68 | type UsergroupGetParams struct { 69 | GetParameters 70 | 71 | Status []int `json:"status,omitempty"` 72 | UserIDs []int `json:"userids,omitempty"` 73 | UsrgrpIDs []int `json:"usrgrpids,omitempty"` 74 | WithGuiAccess []int `json:"with_gui_access,omitempty"` 75 | 76 | SelectTagFilters SelectQuery `json:"selectTagFilters,omitempty"` 77 | SelectUsers SelectQuery `json:"selectUsers,omitempty"` 78 | SelectRights SelectQuery `json:"selectRights,omitempty"` 79 | } 80 | 81 | // Structure to store creation result 82 | type usergroupCreateResult struct { 83 | UsrgrpIDs []int `json:"usrgrpids"` 84 | } 85 | 86 | // Structure to store updation result 87 | type usergroupUpdateResult struct { 88 | UsrgrpIDs []int `json:"usrgrpids"` 89 | } 90 | 91 | // Structure to store deletion result 92 | type usergroupDeleteResult struct { 93 | UsrgrpIDs []int `json:"usrgrpids"` 94 | } 95 | 96 | // UsergroupGet gets usergroups 97 | func (z *Context) UsergroupGet(params UsergroupGetParams) ([]UsergroupObject, int, error) { 98 | 99 | var result []UsergroupObject 100 | 101 | status, err := z.request("usergroup.get", params, &result) 102 | if err != nil { 103 | return nil, status, err 104 | } 105 | 106 | return result, status, nil 107 | } 108 | 109 | // UsergroupCreate creates usergroups 110 | func (z *Context) UsergroupCreate(params []UsergroupObject) ([]int, int, error) { 111 | 112 | var result usergroupCreateResult 113 | 114 | status, err := z.request("usergroup.create", params, &result) 115 | if err != nil { 116 | return nil, status, err 117 | } 118 | 119 | return result.UsrgrpIDs, status, nil 120 | } 121 | 122 | // UsergroupUpdate updates usergroups 123 | func (z *Context) UsergroupUpdate(params []UsergroupObject) ([]int, int, error) { 124 | 125 | var result usergroupUpdateResult 126 | 127 | status, err := z.request("usergroup.update", params, &result) 128 | if err != nil { 129 | return nil, status, err 130 | } 131 | 132 | return result.UsrgrpIDs, status, nil 133 | } 134 | 135 | // UsergroupDelete deletes usergroups 136 | func (z *Context) UsergroupDelete(usergroupIDs []int) ([]int, int, error) { 137 | 138 | var result usergroupDeleteResult 139 | 140 | status, err := z.request("usergroup.delete", usergroupIDs, &result) 141 | if err != nil { 142 | return nil, status, err 143 | } 144 | 145 | return result.UsrgrpIDs, status, nil 146 | } 147 | -------------------------------------------------------------------------------- /usergroup_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testUsergroupName = "testUsergroupName" 10 | testUserAdminID = 1 11 | ) 12 | 13 | func TestUsergroupCRUD(t *testing.T) { 14 | 15 | var z Context 16 | 17 | // Login 18 | loginTest(&z, t) 19 | defer logoutTest(&z, t) 20 | 21 | // Create and delete 22 | ugCreatedIDs := testUsergroupCreate(t, z) 23 | defer testUsergroupDelete(t, z, ugCreatedIDs) 24 | 25 | // Update 26 | testUsergroupUpdate(t, z, ugCreatedIDs) 27 | 28 | // Get 29 | testUsergroupGet(t, z, ugCreatedIDs) 30 | } 31 | 32 | func testUsergroupCreate(t *testing.T, z Context) []int { 33 | 34 | ugCreatedIDs, _, err := z.UsergroupCreate([]UsergroupObject{ 35 | { 36 | Name: testUsergroupName, 37 | }, 38 | }) 39 | if err != nil { 40 | t.Fatal("Usergroup create error:", err) 41 | } 42 | 43 | if len(ugCreatedIDs) == 0 { 44 | t.Fatal("Usergroup create error: empty IDs array") 45 | } 46 | 47 | t.Logf("Usergroup create: success") 48 | 49 | return ugCreatedIDs 50 | } 51 | 52 | func testUsergroupUpdate(t *testing.T, z Context, ugCreatedIDs []int) []int { 53 | 54 | var ugObjects []UsergroupObject 55 | 56 | // Preparing usergroup objects array to update 57 | for _, i := range ugCreatedIDs { 58 | ugObjects = append(ugObjects, UsergroupObject{ 59 | UsrgrpID: i, 60 | UserIDs: []int{testUserAdminID}, 61 | }) 62 | } 63 | 64 | ugUpdatedIDs, _, err := z.UsergroupUpdate(ugObjects) 65 | if err != nil { 66 | t.Fatal("Usergroup update error:", err) 67 | } 68 | 69 | if len(ugUpdatedIDs) == 0 { 70 | t.Fatal("Usergroup update error: empty IDs array") 71 | } 72 | 73 | if reflect.DeepEqual(ugUpdatedIDs, ugCreatedIDs) == false { 74 | t.Fatal("Usergroup update error: IDs arrays for created and updated usergroup are mismatch") 75 | } 76 | 77 | t.Logf("Usergroup update: success") 78 | 79 | return ugUpdatedIDs 80 | } 81 | 82 | func testUsergroupDelete(t *testing.T, z Context, ugCreatedIDs []int) []int { 83 | 84 | ugDeletedIDs, _, err := z.UsergroupDelete(ugCreatedIDs) 85 | if err != nil { 86 | t.Fatal("Usergroup delete error:", err) 87 | } 88 | 89 | if len(ugDeletedIDs) == 0 { 90 | t.Fatal("Usergroup delete error: empty IDs array") 91 | } 92 | 93 | if reflect.DeepEqual(ugDeletedIDs, ugCreatedIDs) == false { 94 | t.Fatal("Usergroup delete error: IDs arrays for created and deleted usergroup are mismatch") 95 | } 96 | 97 | t.Logf("Usergroup delete: success") 98 | 99 | return ugDeletedIDs 100 | } 101 | 102 | func testUsergroupGet(t *testing.T, z Context, ugCreatedIDs []int) []UsergroupObject { 103 | 104 | ugObjects, _, err := z.UsergroupGet(UsergroupGetParams{ 105 | UsrgrpIDs: ugCreatedIDs, 106 | SelectRights: SelectExtendedOutput, 107 | SelectUsers: SelectExtendedOutput, 108 | GetParameters: GetParameters{ 109 | Filter: map[string]interface{}{ 110 | "name": testUsergroupName, 111 | }, 112 | Output: SelectExtendedOutput, 113 | }, 114 | }) 115 | 116 | if err != nil { 117 | t.Error("Usergroup get error:", err) 118 | } else { 119 | if len(ugObjects) == 0 { 120 | t.Error("Usergroup get error: unable to find created usergroup") 121 | } else { 122 | t.Logf("Usergroup get: success") 123 | } 124 | } 125 | 126 | return ugObjects 127 | } 128 | -------------------------------------------------------------------------------- /usermacro.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | // For `UsermacroObject` field: `Type` 4 | const ( 5 | UsermacroTypeText = 0 6 | UsermacroTypeSecret = 1 7 | ) 8 | 9 | // UsermacroObject struct is used to store hostmacro and globalmacro operations results. 10 | // In API docs Global and Host it is a two different object types that are joined in this package 11 | // into one object `UsermacroObject` that includes fields form both API objects. 12 | // The reason is the some other objects do not separates this types. 13 | // 14 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/usermacro/object#host_macro 15 | // and https://www.zabbix.com/documentation/5.0/manual/api/reference/usermacro/object#global_macro 16 | type UsermacroObject struct { 17 | 18 | // Gobal macro fields only 19 | GlobalmacroID int `json:"globalmacroid,omitempty"` 20 | 21 | // Host macro fields only 22 | HostmacroID int `json:"hostmacroid,omitempty"` 23 | HostID int `json:"hostid,omitempty"` 24 | 25 | // Common fields 26 | Macro string `json:"macro,omitempty"` 27 | Value string `json:"value,omitempty"` 28 | Type int `json:"type,omitempty"` // has defined consts, see above 29 | Description string `json:"description,omitempty"` 30 | 31 | Groups []HostgroupObject `json:"groups,omitempty"` 32 | Hosts []HostObject `json:"hosts,omitempty"` 33 | Templates []TemplateObject `json:"templates,omitempty"` 34 | } 35 | 36 | // UsermacroGetParams struct is used for hostmacro get requests 37 | // 38 | // see: https://www.zabbix.com/documentation/5.0/manual/api/reference/usermacro/get#parameters 39 | type UsermacroGetParams struct { 40 | GetParameters 41 | 42 | Globalmacro bool `json:"globalmacro,omitempty"` 43 | GlobalmacroIDs []int `json:"globalmacroids,omitempty"` 44 | GroupIDs []int `json:"groupids,omitempty"` 45 | HostIDs []int `json:"hostids,omitempty"` 46 | HostmacroIDs []int `json:"hostmacroids,omitempty"` 47 | TemplateIDs []int `json:"templateids,omitempty"` 48 | 49 | SelectGroups SelectQuery `json:"selectGroups,omitempty"` 50 | SelectHosts SelectQuery `json:"selectHosts,omitempty"` 51 | SelectTemplates SelectQuery `json:"selectTemplates,omitempty"` 52 | } 53 | 54 | // Structure to store creation result 55 | type hostmacroCreateResult struct { 56 | HostmacroIDs []int `json:"hostmacroids"` 57 | } 58 | 59 | // Structure to store creation global macros result 60 | type globalmacroCreateResult struct { 61 | GlobalmacroIDs []int `json:"globalmacroids"` 62 | } 63 | 64 | // Structure to store deletion result 65 | type hostmacroDeleteResult struct { 66 | HostmacroIDs []int `json:"hostmacroids"` 67 | } 68 | 69 | // Structure to store deletion global macros result 70 | type globalmacroDeleteResult struct { 71 | GlobalmacroIDs []int `json:"globalmacroids"` 72 | } 73 | 74 | // UsermacroGet gets global or host macros according to the given parameters 75 | func (z *Context) UsermacroGet(params UsermacroGetParams) ([]UsermacroObject, int, error) { 76 | 77 | var result []UsermacroObject 78 | 79 | status, err := z.request("usermacro.get", params, &result) 80 | if err != nil { 81 | return nil, status, err 82 | } 83 | 84 | return result, status, nil 85 | } 86 | 87 | // HostmacroCreate creates new hostmacros 88 | func (z *Context) HostmacroCreate(params []UsermacroObject) ([]int, int, error) { 89 | 90 | var result hostmacroCreateResult 91 | 92 | status, err := z.request("usermacro.create", params, &result) 93 | if err != nil { 94 | return nil, status, err 95 | } 96 | 97 | return result.HostmacroIDs, status, nil 98 | } 99 | 100 | // GlobalmacroCreate creates new globalmacros 101 | func (z *Context) GlobalmacroCreate(params []UsermacroObject) ([]int, int, error) { 102 | 103 | var result globalmacroCreateResult 104 | 105 | status, err := z.request("usermacro.createglobal", params, &result) 106 | if err != nil { 107 | return nil, status, err 108 | } 109 | 110 | return result.GlobalmacroIDs, status, nil 111 | } 112 | 113 | // HostmacroDelete deletes hostmacros 114 | func (z *Context) HostmacroDelete(hostmacroIDs []int) ([]int, int, error) { 115 | 116 | var result hostmacroDeleteResult 117 | 118 | status, err := z.request("usermacro.delete", hostmacroIDs, &result) 119 | if err != nil { 120 | return nil, status, err 121 | } 122 | 123 | return result.HostmacroIDs, status, nil 124 | } 125 | 126 | // GlobalmacroDelete deletes globalmacros 127 | func (z *Context) GlobalmacroDelete(globalmacroIDs []int) ([]int, int, error) { 128 | 129 | var result globalmacroDeleteResult 130 | 131 | status, err := z.request("usermacro.deleteglobal", globalmacroIDs, &result) 132 | if err != nil { 133 | return nil, status, err 134 | } 135 | 136 | return result.GlobalmacroIDs, status, nil 137 | } 138 | -------------------------------------------------------------------------------- /usermacro_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | const ( 9 | testHostmacroMacro = "{$TEST_USER_MACRO}" 10 | testHostmacroValue = "testUsermacroValue" 11 | ) 12 | 13 | func TestHostmacroCRUD(t *testing.T) { 14 | 15 | var z Context 16 | 17 | // Login 18 | loginTest(&z, t) 19 | defer logoutTest(&z, t) 20 | 21 | // Preparing auxiliary data 22 | hgCreatedIDs := testHostgroupCreate(t, z) 23 | defer testHostgroupDelete(t, z, hgCreatedIDs) 24 | 25 | tCreatedIDs := testTemplateCreate(t, z, hgCreatedIDs) 26 | defer testTemplateDelete(t, z, tCreatedIDs) 27 | 28 | hCreatedIDs := testHostCreate(t, z, hgCreatedIDs, tCreatedIDs) 29 | defer testHostDelete(t, z, hCreatedIDs) 30 | 31 | // Create and delete 32 | hmCreatedIDs := testHostmacroCreate(t, z, hCreatedIDs[0]) 33 | defer testHostmacroDelete(t, z, hmCreatedIDs) 34 | 35 | // Get 36 | testHostmacroGet(t, z, hmCreatedIDs) 37 | } 38 | 39 | func testHostmacroCreate(t *testing.T, z Context, hCreatedID int) []int { 40 | 41 | hmCreatedIDs, _, err := z.HostmacroCreate([]UsermacroObject{ 42 | { 43 | HostID: hCreatedID, 44 | Macro: testHostmacroMacro, 45 | Value: testHostmacroValue, 46 | }, 47 | }) 48 | if err != nil { 49 | t.Fatal("Hostmacro create error:", err) 50 | } 51 | 52 | if len(hmCreatedIDs) == 0 { 53 | t.Fatal("Hostmacro create error: empty IDs array") 54 | } 55 | 56 | t.Logf("Hostmacro create: success") 57 | 58 | return hmCreatedIDs 59 | } 60 | 61 | func testHostmacroDelete(t *testing.T, z Context, hmCreatedIDs []int) []int { 62 | 63 | hmDeletedIDs, _, err := z.HostmacroDelete(hmCreatedIDs) 64 | if err != nil { 65 | t.Fatal("Hostmacro delete error:", err) 66 | } 67 | 68 | if len(hmDeletedIDs) == 0 { 69 | t.Fatal("Hostmacro delete error: empty IDs array") 70 | } 71 | 72 | if reflect.DeepEqual(hmDeletedIDs, hmCreatedIDs) == false { 73 | t.Fatal("Hostmacro delete error: IDs arrays for created and deleted hostmacro are mismatch") 74 | } 75 | 76 | t.Logf("Hostmacro delete: success") 77 | 78 | return hmDeletedIDs 79 | } 80 | 81 | func testHostmacroGet(t *testing.T, z Context, hmCreatedIDs []int) []UsermacroObject { 82 | 83 | hmObjects, _, err := z.UsermacroGet(UsermacroGetParams{ 84 | HostmacroIDs: hmCreatedIDs, 85 | SelectGroups: SelectExtendedOutput, 86 | SelectHosts: SelectExtendedOutput, 87 | SelectTemplates: SelectExtendedOutput, 88 | GetParameters: GetParameters{ 89 | Filter: map[string]interface{}{ 90 | "macro": testHostmacroMacro, 91 | "value": testHostmacroValue, 92 | }, 93 | Output: SelectExtendedOutput, 94 | }, 95 | }) 96 | 97 | if err != nil { 98 | t.Error("Hostmacro get error:", err) 99 | } else { 100 | if len(hmObjects) == 0 { 101 | t.Error("Hostmacro get error: unable to find created hostmacro") 102 | } else { 103 | t.Logf("Hostmacro get: success") 104 | } 105 | } 106 | 107 | return hmObjects 108 | } 109 | -------------------------------------------------------------------------------- /zabbix.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "strings" 10 | 11 | "github.com/mitchellh/mapstructure" 12 | ) 13 | 14 | // Zabbix select constants 15 | const ( 16 | SelectExtendedOutput = "extend" 17 | SelectCount = "count" 18 | ) 19 | 20 | // For `GetParameters` field: `SortOrder` 21 | const ( 22 | GetParametersSortOrderASC = "ASC" 23 | GetParametersSortOrderDESC = "DESC" 24 | ) 25 | 26 | // Context struct is used for store settings to communicate with Zabbix API 27 | type Context struct { 28 | sessionKey string 29 | host string 30 | } 31 | 32 | // GetParameters struct is used as embedded struct for some other structs within package 33 | // 34 | // see for details: https://www.zabbix.com/documentation/5.0/manual/api/reference_commentary#common_get_method_parameters 35 | type GetParameters struct { 36 | CountOutput bool `json:"countOutput,omitempty"` 37 | Editable bool `json:"editable,omitempty"` 38 | ExcludeSearch bool `json:"excludeSearch,omitempty"` 39 | Filter map[string]interface{} `json:"filter,omitempty"` 40 | Limit int `json:"limit,omitempty"` 41 | Output SelectQuery `json:"output,omitempty"` 42 | PreserveKeys bool `json:"preservekeys,omitempty"` 43 | Search map[string]string `json:"search,omitempty"` 44 | SearchByAny bool `json:"searchByAny,omitempty"` 45 | SearchWildcardsEnabled bool `json:"searchWildcardsEnabled,omitempty"` 46 | SortField []string `json:"sortfield,omitempty"` 47 | SortOrder []string `json:"sortorder,omitempty"` // has defined consts, see above 48 | StartSearch bool `json:"startSearch,omitempty"` 49 | } 50 | 51 | // SelectQuery is used as field type in some structs 52 | type SelectQuery interface{} 53 | 54 | // SelectFields is used as field type in some structs 55 | type SelectFields []string 56 | 57 | type requestData struct { 58 | JSONRPC string `json:"jsonrpc"` 59 | Method string `json:"method"` 60 | Params interface{} `json:"params,omitempty"` 61 | Auth string `json:"auth,omitempty"` 62 | ID int `json:"id"` 63 | } 64 | 65 | type responseData struct { 66 | JSONRPC string `json:"jsonrpc"` 67 | Result interface{} `json:"result"` 68 | Error struct { 69 | Code int `json:"code"` 70 | Message string `json:"message"` 71 | Data string `json:"data"` 72 | } `json:"error"` 73 | ID int `json:"id"` 74 | } 75 | 76 | // Login gets the Zabbix session 77 | func (z *Context) Login(host, user, password string) error { 78 | 79 | var err error 80 | 81 | z.host = host 82 | 83 | r := UserLoginParams{ 84 | User: user, 85 | Password: password, 86 | } 87 | 88 | if z.sessionKey, _, err = z.userLogin(r); err != nil { 89 | return err 90 | } 91 | 92 | return nil 93 | } 94 | 95 | // Logout destroys the Zabbix session 96 | func (z *Context) Logout() error { 97 | 98 | _, _, err := z.userLogout() 99 | 100 | z.sessionKey = "" 101 | 102 | if err != nil { 103 | return err 104 | } 105 | 106 | return nil 107 | } 108 | 109 | func (z *Context) request(method string, params interface{}, result interface{}) (int, error) { 110 | 111 | resp := responseData{ 112 | Result: result, 113 | } 114 | 115 | req := requestData{ 116 | JSONRPC: "2.0", 117 | Method: method, 118 | Params: params, 119 | Auth: z.sessionKey, 120 | ID: 1, 121 | } 122 | 123 | status, err := z.httpPost(req, &resp) 124 | if err != nil { 125 | return status, err 126 | } 127 | 128 | if resp.Error.Code != 0 { 129 | return status, errors.New(resp.Error.Data + " " + resp.Error.Message) 130 | } 131 | 132 | return status, nil 133 | } 134 | 135 | func (z *Context) httpPost(in interface{}, out interface{}) (int, error) { 136 | 137 | s, err := json.Marshal(in) 138 | if err != nil { 139 | return 0, err 140 | } 141 | req, err := http.NewRequest("POST", z.host, strings.NewReader(string(s))) 142 | if err != nil { 143 | return 0, err 144 | } 145 | 146 | // Set headers 147 | req.Header.Add("Content-Type", "application/json-rpc") 148 | 149 | // Make request 150 | res, err := http.DefaultClient.Do(req) 151 | if err != nil { 152 | return 0, err 153 | } 154 | 155 | defer res.Body.Close() 156 | 157 | if res.StatusCode != 200 { 158 | if bodyBytes, err := io.ReadAll(res.Body); err == nil { 159 | return res.StatusCode, errors.New(string(bodyBytes)) 160 | } 161 | } else { 162 | if out != nil { 163 | 164 | rawConf := make(map[string]interface{}) 165 | 166 | dJ := json.NewDecoder(res.Body) 167 | if err := dJ.Decode(&rawConf); err != nil { 168 | return res.StatusCode, fmt.Errorf("json decode error: %v", err) 169 | } 170 | 171 | dM, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ 172 | WeaklyTypedInput: true, 173 | Result: out, 174 | TagName: "json", 175 | }) 176 | if err != nil { 177 | return res.StatusCode, fmt.Errorf("mapstructure create decoder error: %v", err) 178 | } 179 | 180 | if err := dM.Decode(rawConf); err != nil { 181 | return res.StatusCode, fmt.Errorf("mapstructure decode error: %v", err) 182 | } 183 | } 184 | } 185 | 186 | return res.StatusCode, nil 187 | } 188 | -------------------------------------------------------------------------------- /zabbix_test.go: -------------------------------------------------------------------------------- 1 | package zabbix 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | ) 7 | 8 | func loginTest(z *Context, t *testing.T) { 9 | 10 | zbxHost := os.Getenv("ZABBIX_HOST") 11 | if zbxHost == "" { 12 | t.Fatal("Login error: undefined env var `ZABBIX_HOST`") 13 | } 14 | 15 | zbxUsername := os.Getenv("ZABBIX_USERNAME") 16 | if zbxUsername == "" { 17 | t.Fatal("Login error: undefined env var `ZABBIX_USERNAME`") 18 | } 19 | 20 | zbxPassword := os.Getenv("ZABBIX_PASSWORD") 21 | if zbxPassword == "" { 22 | t.Fatal("Login error: undefined env var `ZABBIX_PASSWORD`") 23 | } 24 | 25 | if err := z.Login(zbxHost, zbxUsername, zbxPassword); err != nil { 26 | t.Fatal("Login error: ", err) 27 | } else { 28 | t.Logf("Login: success") 29 | } 30 | } 31 | 32 | func logoutTest(z *Context, t *testing.T) { 33 | 34 | if err := z.Logout(); err != nil { 35 | t.Fatal("Logout error: ", err) 36 | } else { 37 | t.Logf("Logout: success") 38 | } 39 | } 40 | --------------------------------------------------------------------------------