PowerShellでMackerelのAPIをたたいてみた

一通り叩いてみました。
一覧はこちらです。
[API仕様（v0）](http://help-ja.mackerel.io/entry/spec/api/v0)

一部、使い方がよくわからず確認できませんでした。


# 準備
## ヘッダーを変数に格納
X-Api-Keyのみ必須

```ps1:コマンド
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-API-KEY", '12345678901234567890123456789012345678901234')
```


# ホスト
## ホスト情報の登録

```text:仕様
POST /api/v0/hosts
```

```ps1:コマンド
$hostinfo = @"
{
    "name":  "ip-172-31-5-222",
    "meta":  {
        "agent-name":  "",
        "agent-revision":  "",
        "agent-version":  "",
        "block_device":  "",
        "cloud":  "",
        "cpu":  "",
        "filesystem":  "",
        "kernel":  "",
        "memory":  ""
    }
}
"@



Invoke-RestMethod -Uri https://mackerel.io/api/v0/hosts -Method Post -Headers $headers -Body $hostinfo -ContentType 'application/json' | ConvertTo-Json
```

```json:結果
{
    "id":  "12345678901"
}
```

## ホスト情報の取得
```text:仕様
GET /api/v0/hosts/<hostId>
```

```ps1:コマンド
$hostid='***********'
Invoke-RestMethod -Uri https://mackerel.io/api/v0/hosts/$hostid -Method Get -Headers $headers | ConvertTo-Json
```

```json:結果
{
    "host":  {
                 "name":  "ip-172-31-5-181",
                 "nickname":  null,
                 "displayName":  "ip-172-31-5-181",
                 "meta":  {
                              "agent-name":  "mackerel-agent/0.20.1 (Revision e2f8eea)",
                              "agent-revision":  "e2f8eea",
                              "agent-version":  "0.20.1",
                              "block_device":  "@{xvda=}",
                              "cloud":  "@{metadata=; provider=ec2}",
                              "cpu":  "",
                              "filesystem":  "@{/dev/xvda1=; devtmpfs=; tmpfs=}",
                              "kernel":  "@{machine=x86_64; name=Linux; os=GNU/Linux; release=3.14.48-33.39.amzn1.x86_64; version=#1 SMP Tue Jul 14 23:43:07 UTC 2015}",
                              "memory":  "@{active=96488kB; anon_pages=15940kB; bounce=0kB; buffers=15192kB; cached=132992kB; commit_limit=510092kB; committed_as=62384kB; dirty=0kB; free=812880kB; inactive=67644kB; mapped=7452kB; nfs_unstable=0kB; page_tables=1816kB; slab=30512kB; slab_reclaimable=23232kB; slab_unreclaim=7280kB; swap_cached=0kB; swap_free=0kB; swap_total=0kB; total=1020184kB; vmalloc_chunk=34359732811kB; vmalloc_total=34359738367kB; vmalloc_used=2408kB; writeback=0kB}"
                          },
                 "type":  "unknown",
                 "status":  "working",
                 "memo":  "",
                 "isRetired":  false,
                 "id":  "2tkWrBNdu1Q",
                 "createdAt":  1439969560,
                 "roles":  {
                               "Linux":  "Management"
                           },
                 "interfaces":  [
                                    "@{ipAddress=172.31.5.181; ipv6Address=fe80::497:4dff:feac:3601; macAddress=06:97:4d:ac:36:01; name=eth0}"
                                ]
             }
}
```

## ホスト情報の更新
```text:仕様
PUT /api/v0/hosts/<hostId>
```

```ps1:コマンド
$hostinfo = @"
{
    "name":  "ip-172-31-5-111",
    "meta":  {
        "agent-name":  "",
        "agent-revision":  "",
        "agent-version":  "",
        "block_device":  "",
        "cloud":  "",
        "cpu":  "",
        "filesystem":  "",
        "kernel":  "",
        "memory":  ""
    }
}
"@



$hostid='12345678901'

Invoke-RestMethod -Uri https://mackerel.io/api/v0/hosts/$hostid -Method Put -Headers $headers -Body $hostinfo -ContentType 'application/json' | ConvertTo-Json
```

```json:結果
{
    "id":  "12345678901"
}
```

## ホストのステータスの更新
```text:仕様
POST /api/v0/hosts/<hostId>/status
```

```ps1:コマンド
$status = @"
{
  "status": "maintenance"
}
"@



$hostid='12345678901'

Invoke-RestMethod -Uri https://mackerel.io/api/v0/hosts/$hostid/status -Method Post -Headers $headers -Body $status -ContentType 'application/json' | ConvertTo-Json
```

```json:結果
{
    "success":  true
}
```

## ホストの退役
```text:仕様
POST /api/v0/hosts/<hostId>/retire
```

```ps1:コマンド
$hostid='12345678901'

Invoke-RestMethod -Uri https://mackerel.io/api/v0/hosts/$hostid/retire -Method Post -Headers $headers -Body $status -ContentType 'application/json' | ConvertTo-Json
```

```json:結果
{
    "success":  true
}

```

## ホストの一覧
```text:仕様
GET /api/v0/hosts.json
```

```ps1:コマンド
Invoke-RestMethod -Uri https://mackerel.io/api/v0/hosts.json -Method Get -Headers $headers | ConvertTo-Json
```

```json:結果
{
    "hosts":  [
                  {
                      "name":  "ip-172-31-5-181",
                      "nickname":  null,
                      "displayName":  "ip-172-31-5-181",
                      "meta":  "@{agent-name=mackerel-agent/0.20.1 (Revision e2f8eea); agent-revision=e2f8eea; agent-version=0.20.1; block_device=; cloud=; cpu=System.Object[]; filesystem=; kernel=; memory=}",
                      "type":  "unknown",
                      "status":  "working",
                      "memo":  "",
                      "isRetired":  false,
                      "id":  "***********",
                      "createdAt":  1439969560,
                      "roles":  "@{Linux=System.Object[]}",
                      "interfaces":  ""
                  },
                  {
                      "name":  "WIN-B4UEJ133OJN",
                      "nickname":  null,
                      "displayName":  "WIN-B4UEJ133OJN",
                      "meta":  "@{agent-name=mackerel-agent/0.20.1 (Revision e2f8eea); agent-revision=e2f8eea; agent-version=0.20.1; block_device=; cpu=System.Object[]; filesystem=; kernel=; memory=}",
                      "type":  "unknown",
                      "status":  "working",
                      "memo":  "",
                      "isRetired":  false,
                      "id":  "***********",
                      "createdAt":  1439969458,
                      "roles":  "@{Windows=System.Object[]}",
                      "interfaces":  ""
                  }
              ]
}
```


# メトリック
## メトリックの投稿
```text:仕様
POST /api/v0/tsdb
```

```ps1:コマンド
$hostid='***********'

$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$date = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds
$epoch_jst = [math]::Truncate($date)
$epoch_utc = $epoch_jst - 32400

$metric=@"
[{
    "hostId": `"$hostid`",
    "name": "custom.foo.bar",
    "time": $epoch_utc,
    "value": 30
}]
"@



Invoke-RestMethod -Uri https://mackerel.io/api/v0/tsdb -Method Post -Headers $headers -Body $metric -ContentType 'application/json' | ConvertTo-Json
```

```text:結果
{
    "success":  true
}
```

## メトリックの最新値の取得
```text:仕様
GET /api/v0/tsdb/latest
```

```ps1:コマンド
$hostid='***********'
$name='custom.foo.bar'
$url=@"
https://mackerel.io/api/v0/tsdb/latest?hostId=$hostid&name=$name
"@



Invoke-RestMethod -Uri $url -Method Get -Headers $headers | ConvertTo-Json
```

```text:結果
{
    "tsdbLatest":  {
                       "***********":  {
                                           "custom.foo.bar":  "@{time=1440345600; value=30.0}"
                                       }
                   }
}
```

## グラフ定義の投稿（未確認）
```text:仕様
POST /api/v0/graph-defs/create
```

```ps1:コマンド
$graphname='custom.foo'
$graphlabel='foo001'

$metricname='bar'
$metriclabel='bar002'

$graph=@"
[
  {
    "graphs": {
      ${graphname}: {
        "label": "${graphlabel}",
        "unit": "integer",
        "metrics": [
          {
            "name": "${metricname}",
            "label": "${metriclabel}",
            "stacked": false
          }
        ]
      }
    }
  }
]
"@



Invoke-RestMethod -Uri https://mackerel.io/api/v0/graph-defs/create -Method Post -Headers $headers -Body $graph -ContentType 'application/json' | ConvertTo-Json
```

```text:結果
未確認

Invoke-RestMethod : {"error":"Invalid Parameter: obj[0].name error.path.missing."}
発生場所 行:1 文字:1
+ Invoke-RestMethod -Uri https://mackerel.io/api/v0/graph-defs/create -Method Post ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod]、WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
```

## サービスメトリックの投稿
```text:仕様
POST /api/v0/services/<serviceName>/tsdb
```

```ps1:コマンド
$metricname='Sample.foo'
$servicename='Linux'

$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$date = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds
$epoch_jst = [math]::Truncate($date)
$epoch_utc = $epoch_jst - 32400

$metric=@"
[{
    "name": "Sample.foo",
    "time": $epoch_utc,
    "value": 30
}]
"@



Invoke-RestMethod -Uri https://mackerel.io/api/v0/services/${servicename}/tsdb -Method Post -Headers $headers -Body $metric -ContentType 'application/json' | ConvertTo-Json
```

```text:結果
{
    "success":  true
}
```

## チェック監視結果の投稿（未確認）
```text:仕様
POST /api/v0/monitoring/checks/report
```

```ps1:コマンド
$hostid='***********'

$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
$date = (New-TimeSpan -Start $date1 -End $date2).TotalSeconds
$epoch_jst = [math]::Truncate($date)
$epoch_utc = $epoch_jst - 32400

$report=@"
{
  "reports": [
    {
      "source": [
        {
          "type": "host",
          "hostId": "${hostid}"
        }
      ],
      "name": "Service Status",
      "status": "CRITICAL",
      "message": "Service is stopped.",
      "occurredAt": ${epoch_utc}
    }
  ] 
}
"@



Invoke-RestMethod -Uri https://mackerel.io/api/v0/monitoring/checks/report -Method Post -Headers $headers -Body $report -ContentType 'application/json' | ConvertTo-Json
```

```text:結果
未確認

Invoke-RestMethod : {"error":"Invalid Parameter: obj.reports[0].source error.expected.jsstring."}
発生場所 行:1 文字:1
+ Invoke-RestMethod -Uri https://mackerel.io/api/v0/monitoring/checks/report -Meth ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod]、WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
```


# 監視設定
## 監視設定の登録
```text:仕様
POST /api/v0/monitors
```

```ps1:コマンド
$monitorsettings = @"
{
    "type":  "host",
    "name":  "DISK %",
    "metric":  "disk%",
    "operator":  ">",
    "warning":  70.0,
    "critical":  90.0,
    "duration":  3
}
"@



Invoke-RestMethod -Uri https://mackerel.io/api/v0/monitors -Method Post -Headers $headers -Body $monitorsettings -ContentType 'application/json' | ConvertTo-Json

```

```json:結果
{
    "id":  "***********",
    "type":  "host",
    "name":  "DISK%",
    "metric":  "disk%",
    "operator":  "\u003e",
    "warning":  70.0,
    "critical":  90.0,
    "duration":  3,
    "scopes":  [

               ],
    "excludeScopes":  [

                      ]
}
```

## 監視設定の取得
```text:仕様
GET /api/v0/monitors
```

```ps1:コマンド
Invoke-RestMethod -Uri https://mackerel.io/api/v0/monitors -Method Get -Headers $headers | ConvertTo-Json
```

```json:結果
{
    "monitors":  [
                     {
                         "id":  "***********",
                         "type":  "connectivity",
                         "scopes":  "",
                         "excludeScopes":  ""
                     },
                     {
                         "id":  "***********",
                         "type":  "host",
                         "name":  "CPU %",
                         "metric":  "cpu%",
                         "operator":  "\u003e",
                         "warning":  70.0,
                         "critical":  90.0,
                         "duration":  3,
                         "scopes":  "",
                         "excludeScopes":  ""
                     }
                 ]
}
```

## 監視設定の更新
```text:仕様
PUT /api/v0/monitors/<monitorId>
```

```ps1:コマンド

$monitorsettings = @"
{
    "type":  "host",
    "name":  "DISK %",
    "metric":  "disk%",
    "operator":  ">",
    "warning":  70.0,
    "critical":  80.0,
    "duration":  3
}
"@



$monitorid='***********'

Invoke-RestMethod -Uri https://mackerel.io/api/v0/monitors/$monitorid -Method Put -Headers $headers -Body $monitorsettings -ContentType 'application/json' | ConvertTo-Json
```

```json:結果
{
    "id":  "***********"
}
```

## 監視設定の削除
```text:仕様
DELETE/api/v0/monitors/<monitorId>
```

```ps1:コマンド
$monitorid = '***********'

Invoke-RestMethod -Uri https://mackerel.io/api/v0/monitors/$monitorid -Method Delete -Headers $headers -ContentType 'application/json' | ConvertTo-Json
```

```json:結果
{
    "id":  "***********",
    "type":  "host",
    "name":  "DISK %",
    "metric":  "disk%",
    "operator":  "\u003e",
    "warning":  70.0,
    "critical":  90.0,
    "duration":  3,
    "scopes":  [

               ],
    "excludeScopes":  [

                      ]
}
```