#!/usr/bin/python

import threading
import sys
import rados
import socket
import time
import os
import boto3
import boto.s3.connection
from boto.s3.key import Key

exitFlag = 0
parentname = "/"
#name = "testfolder"
#data = "000100110000001100100001000111111011111001000010010101011001000010010100101011111111111010"
pool = 'rbd'
#access_key = 'AKIAPISHRUTQABC746AQ'
#secret_key = '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'

class multithread (threading.Thread):
	def __init__(self, threadID, name, counter):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.counter = counter
	def run(self):
		ls(self.name, parentname, pool)
		#syncobject(self.name, name, data, pool, access_key, secret_key)

def mkdir(threadName,parentname, pool):
	#hostname = socket.gethostname()
	#objectname = hostname + threadName

	try:
		cluster = rados.Rados(conffile='/etc/ceph/ceph.conf')
	except TypeError as e:
		print threadName, ' - Argument validation error: ', e
		raise e

	print threadName, " - Created cluster handle."

	try:
		cluster.connect()
	except Exception as e:
		print threadName, " - connection error: ", e
		raise e
	finally:
		print threadName, " - Connected to the cluster."

	print threadName, " - Creating a context for the pool."
	if not cluster.pool_exists(pool):
		raise RuntimeError('No pool exists')
	ioctx = cluster.open_ioctx(pool)

	print threadName, " - Writing object with contents to pool."
	ioctx.set_xattr(name, "parentname", parentname)
	ioctx.set_xattr(name, "mtime", time.asctime( time.localtime(time.time()) ))

	print threadName, " - Closing the connection."
	ioctx.close()

	print threadName, " - Shutting down the handle."
	cluster.shutdown()

def syncobject(threadName, name, data, pool, access_key, secret_key):

	conn = boto.s3.connect_to_region('cn-north-1',
		aws_access_key_id = access_key,
		aws_secret_access_key = secret_key,
		#host = 'objects.dreamhost.com',
		#is_secure=False,			   # uncomment if you are not using ssl
		calling_format = boto.s3.connection.OrdinaryCallingFormat(),
		)

#	for bucket in conn.get_all_buckets():
#		print "{name}\t{created}".format(
#			name = bucket.name,
#			created = bucket.creation_date,
#		)

	bucket = conn.get_bucket('hsw-dfs-test')
	k = Key(bucket)
	k.key = name
	k.set_contents_from_string(data)
	print k.last_modified

#	for key in bucket:
#		print key.name, key.last_modified
#		if key.last_modified != time.ctime(os.path.getmtime(__file__)):
#			print 'YES!'

# Create new threads
for i in range(0,1):
	obj = multithread(i, "Thread-%d" %i, i)
	obj.start()
