Skip to content

Instantly share code, notes, and snippets.

@notmyname
Created May 10, 2016 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notmyname/af8c99f04e7b8bedcff3c44827d602d7 to your computer and use it in GitHub Desktop.
Save notmyname/af8c99f04e7b8bedcff3c44827d602d7 to your computer and use it in GitHub Desktop.
# makes request to a swift cluster
import asyncdispatch
import strutils
import httpclient
import json
import strtabs
const
auth_url = "http://192.168.56.2:8080/auth/v1.0"
username = "test:tester"
apikey = "testing"
tenant_id = "test" # unused
region = "" # unused
objects_to_put = 1000
type
AuthCreds = tuple[storage_url, token: string]
proc auth_v1(url, username, key: string): AuthCreds =
let client = newAsyncHttpClient(userAgent="swift_pusher/0.1")
client.headers["X-Auth-Key"] = key
client.headers["X-Auth-User"] = username
var resp = waitFor(get(client, url))
result = (storage_url: resp.headers["x-storage-url"],
token: resp.headers["x-auth-token"])
proc auth_v2(url, username, key, tenant_id, region: string): AuthCreds =
var
request_body = %{"auth": %{"passwordCredentials":
%{"username": %username, "password": %apikey},
"tenantId": %tenant_id}}
headers = "Content-Type: application/json\r\n"
resp = post(url, extraHeaders=headers, body= $request_body)
token, storage_url: string
if resp.status == "200 OK": # and resp.headers content type is json
let catalog = parseJson(resp.body)
token = ($catalog["access"]["token"]["id"])[1.. ^2]
for thing in catalog["access"]["serviceCatalog"]:
var t: string = ($(thing["type"]))[1.. ^2]
if t == "object-store":
for endpoint in thing["endpoints"]:
var r: string = ($(endpoint["region"]))[1.. ^2]
if r == region:
storage_url = ($(endpoint["publicURL"]))[1.. ^2]
return (storage_url: storage_url, token: token)
else:
continue
else:
discard # do something interesting
result = (storage_url: storage_url, token: token)
proc put_objects(creds: AuthCreds) =
var container, object_name: string
var resp: Response
var responses: seq[Future[Response]]
let client = newAsyncHttpClient(userAgent="swift_pusher/0.1")
client.headers["X-Auth-Token"] = creds.token
container = "/nim_test_container"
resp = waitFor(request(client, creds.storage_url & container, httpPUT))
for i in 1..objects_to_put:
object_name = creds.storage_url & container & "/nimtest_" & $i
client.headers["Content-Length"] = "0"
var r = request(client, object_name, httpPUT)
responses.add(r) # need to figure out the asyncdispatch stuff
for r in responses:
resp = waitFor(r)
if resp.status != "200 OK":
echo("Bad response" & $resp)
close(client)
var creds: AuthCreds
#creds = auth_v2(auth_url, username, apikey, tenant_id, region)
creds = auth_v1(auth_url, username, apikey)
if creds.token == nil:
discard # do soemthing like log or exit
put_objects(creds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment