Edits history of script submission #23960 for ' Create maintenance (zabbix)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create maintenance
     * Create a one-time maintenance window (maintenance.create) on host IDs and/or host group IDs, starting at start_time (ISO 8601, default now) for duration_minutes (at least 5; Zabbix rounds times down to the minute). Data keeps being collected (problems are suppressed) unless without_data_collection is set. Names must be unique: include the flow job ID, for example, so list_maintenances can find it again. Returns the maintenanceid.
     */
    export async function main(
      auth: RT.Zabbix,
      name: string,
      duration_minutes: number,
      host_ids: string[] | undefined,
      group_ids: string[] | undefined,
      start_time: string | undefined,
      without_data_collection: boolean | undefined,
      description: string | undefined
    ) {
      if (!host_ids?.length && !group_ids?.length) {
        throw new Error("Provide at least one host ID or host group ID")
      }
      // Zabbix rounds times down to the minute: start on the minute and round the
      // end up, so the window covers at least the requested duration.
      const requested = start_time ? new Date(start_time).getTime() : Date.now()
      const start = Math.floor(requested / 60000) * 60
      if (Number.isNaN(start)) {
        throw new Error(`Invalid start_time: ${start_time}`)
      }
      const end = Math.ceil((requested + duration_minutes * 60000) / 60000) * 60
      const period = end - start
    
      const params: { [key: string]: any } = {
        name,
        maintenance_type: without_data_collection ? 1 : 0,
        active_since: start,
        active_till: start + period,
        timeperiods: [{ timeperiod_type: 0, start_date: start, period }],
        description: description || undefined,
      }
      if (host_ids?.length) {
        params.hosts = host_ids.map((hostid) => ({ hostid }))
      }
      if (group_ids?.length) {
        params.groups = group_ids.map((groupid) => ({ groupid }))
      }
    
      const result = await call(auth, "maintenance.create", params)
      return { maintenanceid: result.maintenanceids[0] }
    }
    
    async function call(auth: RT.Zabbix, method: string, params: any) {
      const response = await fetch(
        `${auth.base_url.replace(/\/+$/, "").replace(/\/api_jsonrpc\.php$/, "")}/api_jsonrpc.php`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json-rpc",
            Accept: "application/json",
          },
          body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const text = await response.text()
      let data: any
      try {
        data = JSON.parse(text)
      } catch {
        throw new Error(
          `Not a JSON-RPC response (check base_url): ${text.slice(0, 300)}`
        )
      }
      if (data.error) {
        throw new Error(
          `${data.error.code} ${data.error.message} ${data.error.data ?? ""}`
        )
      }
      return data.result
    }
    

    Submitted by hugo989 3 hours ago