Esempio n. 1
0
    def test_authenticate_success(self):
        cs = client.Client("username", "password", "project_id", "auth_url")
        management_url = 'https://localhost/v1.1/443470'
        auth_response = utils.TestResponse({
            'status_code': 204,
            'headers': {
                'x-server-management-url': management_url,
                'x-auth-token': '1b751d74-de0c-46ae-84f0-915744b582d1',
            },
        })
        mock_request = mock.Mock(return_value=(auth_response))

        @mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            cs.client.authenticate()
            headers = {
                'Accept': 'application/json',
                'X-Auth-User': '******',
                'X-Auth-Key': 'password',
                'X-Auth-Project-Id': 'project_id',
                'User-Agent': cs.client.USER_AGENT
            }
            mock_request.assert_called_with(
                "GET",
                cs.client.auth_url,
                headers=headers,
                **self.TEST_REQUEST_BASE)

            self.assertEqual(cs.client.management_url,
                             auth_response.headers['x-server-management-url'])
            self.assertEqual(cs.client.auth_token,
                             auth_response.headers['x-auth-token'])

        test_auth_call()
Esempio n. 2
0
    def test_ambiguous_endpoints(self):
        cs = client.Client("username",
                           "password",
                           "project_id",
                           "auth_url/v2.0",
                           service_type='compute')
        resp = {
            "access": {
                "token": {
                    "expires": "12345",
                    "id": "FAKE_ID",
                },
                "serviceCatalog": [
                    {
                        "adminURL":
                        "http://*****:*****@mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            self.assertRaises(exceptions.AmbiguousEndpoints,
                              cs.client.authenticate)

        test_auth_call()
Esempio n. 3
0
    def test_auth_manual(self):
        cs = client.Client("username", "password", "project_id", "auth_url")

        @mock.patch.object(cs.client, 'authenticate')
        def test_auth_call(m):
            cs.authenticate()
            m.assert_called()

        test_auth_call()
Esempio n. 4
0
    def test_authenticate_failure(self):
        cs = client.Client("username", "password", "project_id", "auth_url")
        auth_response = utils.TestResponse({"status_code": 401})
        mock_request = mock.Mock(return_value=(auth_response))

        @mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            self.assertRaises(exceptions.Unauthorized, cs.client.authenticate)

        test_auth_call()
Esempio n. 5
0
def vsmclient(request):
    key_vsm_pass = getattr(settings,'KEYSTONE_VSM_SERVICE_PASSWORD')
    key_url = getattr(settings, 'OPENSTACK_KEYSTONE_URL')
    c = vsm_client.Client('vsm',
                          key_vsm_pass,
                          'service',
                          key_url,
                          extensions=[ExtensionManager('PoolUsageManager',
                                                PoolUsageManager),
                                      ExtensionManager('AppNodeManager',
                                                AppNodeManager)])
    return c
Esempio n. 6
0
    def test_auth_automatic(self):
        cs = client.Client("username", "password", "project_id", "auth_url")
        http_client = cs.client
        http_client.management_url = ''
        mock_request = mock.Mock(return_value=(None, None))

        @mock.patch.object(http_client, 'request', mock_request)
        @mock.patch.object(http_client, 'authenticate')
        def test_auth_call(m):
            http_client.get('/')
            m.assert_called()
            mock_request.assert_called()

        test_auth_call()
Esempio n. 7
0
    def test_authenticate_failure(self):
        cs = client.Client("username", "password", "project_id",
                           "auth_url/v2.0")
        resp = {"unauthorized": {"message": "Unauthorized", "code": "401"}}
        auth_response = utils.TestResponse({
            "status_code": 401,
            "text": json.dumps(resp),
        })

        mock_request = mock.Mock(return_value=(auth_response))

        @mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            self.assertRaises(exceptions.Unauthorized, cs.client.authenticate)

        test_auth_call()
Esempio n. 8
0
from vsmclient.v1 import client
from vsmclient.v1 import appnodes


class ExtensionManager:
    def __init__(self, name, manager_class):
        self.name = name
        self.manager_class = manager_class


vsmclient = client.Client(
    'vsm',
    'keystone_vsm_password',
    'service',
    auth_url='http://127.0.0.1:5000/v2.0/',
    extensions=[ExtensionManager('AppNodeManager', appnodes.AppNodeManager)])

#ip_list = ["10.239.131.170", "10.239.131.255"]
##ip_list = '10.239.131.255'
#post = vsmclient.AppNodeManager.create(ip_list)
#
#print post

get = vsmclient.AppNodeManager.list()
print get

#for i in get:
#    i.update(ssh_status='running', log_info='test')
#
j = 0
for i in get:
Esempio n. 9
0
    def __init__(self, app, conf):
        #self.LOG = logging.getLogger(conf.get('log_name', __name__))
        logger = logging.getLogger()
        handler = logging.FileHandler("/var/log/vsm/vsm-client.log")
        logger.addHandler(handler)
        logger.setLevel(logging.NOTSET)
        self.LOG = logger
        self.LOG.info('Starting vsm auth_token middleware')
        self.conf = conf
        self.app = app

        # delay_auth_decision means we still allow unauthenticated requests
        # through and we let the downstream service make the final decision
        self.delay_auth_decision = (self._conf_get('delay_auth_decision')
                                    in (True, 'true', 't', '1', 'on', 'yes',
                                        'y'))

        # where to find the auth service (we use this to validate tokens)
        self.auth_host = self._conf_get('auth_host')
        self.auth_port = int(self._conf_get('auth_port'))
        self.auth_protocol = self._conf_get('auth_protocol')
        if not self._conf_get('http_handler'):
            if self.auth_protocol == 'http':
                self.http_client_class = httplib.HTTPConnection
            else:
                self.http_client_class = httplib.HTTPSConnection
        else:
            # Really only used for unit testing, since we need to
            # have a fake handler set up before we issue an http
            # request to get the list of versions supported by the
            # server at the end of this initialization
            self.http_client_class = self._conf_get('http_handler')

        self.auth_admin_prefix = self._conf_get('auth_admin_prefix')
        self.auth_uri = self._conf_get('auth_uri')
        if self.auth_uri is None:
            self.auth_uri = '%s://%s:%s' % (self.auth_protocol, self.auth_host,
                                            self.auth_port)

        # SSL
        self.cert_file = self._conf_get('certfile')
        self.key_file = self._conf_get('keyfile')

        # signing

        self.signing_dirname = self._conf_get('signing_dir')
        if self.signing_dirname is None:
            self.signing_dirname = tempfile.mkdtemp(prefix='vsm-signing-')
        self.LOG.info('Using %s as cache directory for signing certificate' %
                      self.signing_dirname)
        if os.path.exists(self.signing_dirname):
            if not os.access(self.signing_dirname, os.W_OK):
                raise ConfigurationError('unable to access signing_dir %s' %
                                         self.signing_dirname)
            if os.stat(self.signing_dirname).st_uid != os.getuid():
                self.LOG.warning('signing_dir is not owned by %s' %
                                 os.getlogin())
            current_mode = stat.S_IMODE(os.stat(self.signing_dirname).st_mode)
            if current_mode != stat.S_IRWXU:
                self.LOG.warning('signing_dir mode is %s instead of %s' %
                                 (oct(current_mode), oct(stat.S_IRWXU)))
        else:
            os.makedirs(self.signing_dirname, stat.S_IRWXU)

        val = '%s/signing_cert.pem' % self.signing_dirname
        self.signing_cert_file_name = val
        val = '%s/cacert.pem' % self.signing_dirname
        self.ca_file_name = val
        val = '%s/revoked.pem' % self.signing_dirname
        self.revoked_file_name = val

        # Credentials used to verify this component with the Auth service since
        # validating tokens is a privileged call
        self.admin_token = self._conf_get('admin_token')
        self.admin_token_expiry = None
        self.admin_user = self._conf_get('admin_user')
        self.admin_password = self._conf_get('admin_password')
        self.admin_tenant_name = self._conf_get('admin_tenant_name')
        auth_url = 'http://%s:5000/v2.0/' % self.auth_host
        self.ec = client.Client(self.admin_user, self.admin_password,
                                self.admin_tenant_name, auth_url)

        # Token caching via memcache
        self._cache = None
        self._use_vsm_cache = False
        self._cache_initialized = False  # cache already initialzied?
        # memcache value treatment, ENCRYPT or MAC
        self._memcache_security_strategy = \
            self._conf_get('memcache_security_strategy')
        if self._memcache_security_strategy is not None:
            self._memcache_security_strategy = \
                self._memcache_security_strategy.upper()
        self._memcache_secret_key = \
            self._conf_get('memcache_secret_key')
        self._assert_valid_memcache_protection_config()
        # By default the token will be cached for 5 minutes
        self.token_cache_time = int(self._conf_get('token_cache_time'))
        self._token_revocation_list = None
        self._token_revocation_list_fetched_time = None
        self.token_revocation_list_cache_timeout = datetime.timedelta(
            seconds=self._conf_get('revocation_cache_time'))
        http_connect_timeout_cfg = self._conf_get('http_connect_timeout')
        self.http_connect_timeout = (http_connect_timeout_cfg
                                     and int(http_connect_timeout_cfg))
        self.auth_version = None
Esempio n. 10
0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

from vsmclient.v1 import client
from vsmclient.v1 import performance_metrics

class ExtensionManager:
    def __init__(self, name, manager_class):
        self.name = name
        self.manager_class = manager_class

vsmclient = client.Client(
                 'vsm',
                 'keystone_vsm_password',
                 'service',
                 auth_url='http://127.0.0.1:5000/v2.0/',
                 extensions=[ExtensionManager('PerformanceMetricsManager',
                                                performance_metrics.PerformanceMetricsManager)])


search_opt = {'metrics_name':'iops','timestamp_start':1234566}
get = vsmclient.PerformanceMetricsManager.list(search_opt=search_opt)
print get



Esempio n. 11
0
from vsmclient.v1 import client
from vsmclient.v1 import pool_usages


class ExtensionManager:
    def __init__(self, name, manager_class):
        self.name = name
        self.manager_class = manager_class


vsmclient = client.Client('vsm',
                          'keystone_vsm_password',
                          'service',
                          auth_url='http://127.0.0.1:5000/v2.0/',
                          extensions=[
                              ExtensionManager('PoolUsageManager',
                                               pool_usages.PoolUsageManager)
                          ])
#
pool_id = ['1', '2', '3']
post = vsmclient.PoolUsageManager.create(pool_id)

print post

get = vsmclient.PoolUsageManager.list()
print get

for i in get:
    i.update(attach_status='success')

j = 0
Esempio n. 12
0
    def test_authenticate_tenant_id(self):
        cs = client.Client("username", "password", auth_url="auth_url/v2.0",
                           tenant_id='tenant_id', service_type='compute')
        resp = {
            "access": {
                "token": {
                    "expires": "12345",
                    "id": "FAKE_ID",
                    "tenant": {
                        "description": None,
                        "enabled": True,
                        "id": "tenant_id",
                        "name": "demo"
                    }  # tenant associated with token
                },
                "serviceCatalog": [
                    {
                        "type": "compute",
                        "endpoints": [
                            {
                                "region": "RegionOne",
                                "adminURL": "http://*****:*****@mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            cs.client.authenticate()
            headers = {
                'User-Agent': cs.client.USER_AGENT,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
            body = {
                'auth': {
                    'passwordCredentials': {
                        'username': cs.client.user,
                        'password': cs.client.password,
                    },
                    'tenantId': cs.client.tenant_id,
                },
            }

            token_url = cs.client.auth_url + "/tokens"
            mock_request.assert_called_with(
                "POST",
                token_url,
                headers=headers,
                data=json.dumps(body),
                allow_redirects=True,
                **self.TEST_REQUEST_BASE)

            endpoints = resp["access"]["serviceCatalog"][0]['endpoints']
            public_url = endpoints[0]["publicURL"].rstrip('/')
            self.assertEqual(cs.client.management_url, public_url)
            token_id = resp["access"]["token"]["id"]
            self.assertEqual(cs.client.auth_token, token_id)
            tenant_id = resp["access"]["token"]["tenant"]["id"]
            self.assertEqual(cs.client.tenant_id, tenant_id)

        test_auth_call()
Esempio n. 13
0
    def test_auth_redirect(self):
        cs = client.Client("username", "password", "project_id",
                           "auth_url/v1", service_type='compute')
        dict_correct_response = {
            "access": {
                "token": {
                    "expires": "12345",
                    "id": "FAKE_ID",
                },
                "serviceCatalog": [
                    {
                        "type": "compute",
                        "endpoints": [
                            {
                                "adminURL": "http://*****:*****@mock.patch.object(requests, "request", mock_request)
        def test_auth_call():
            cs.client.authenticate()
            headers = {
                'User-Agent': cs.client.USER_AGENT,
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
            body = {
                'auth': {
                    'passwordCredentials': {
                        'username': cs.client.user,
                        'password': cs.client.password,
                    },
                    'tenantName': cs.client.projectid,
                },
            }

            token_url = cs.client.auth_url + "/tokens"
            mock_request.assert_called_with(
                "POST",
                token_url,
                headers=headers,
                data=json.dumps(body),
                allow_redirects=True,
                **self.TEST_REQUEST_BASE)

            resp = dict_correct_response
            endpoints = resp["access"]["serviceCatalog"][0]['endpoints']
            public_url = endpoints[0]["publicURL"].rstrip('/')
            self.assertEqual(cs.client.management_url, public_url)
            token_id = resp["access"]["token"]["id"]
            self.assertEqual(cs.client.auth_token, token_id)

        test_auth_call()
Esempio n. 14
0
from vsmclient.v1 import client
from vsmclient import exceptions

vsmclient = client.Client('vsm',
                          'keystone_vsm_password',
                          'service',
                          auth_url='http://127.0.0.1:5000/v2.0/')

ret = vsmclient.vsm_settings.list(detailed=True)
print ret

err1 = {'name': '', 'value': 'csefwe'}

err2 = {'name': '123', 'value': 'dfweqw'}

#try:
#    ret = vsmclient.vsm_settings.create(err1)
#except exceptions.BadRequest as e:
#    print e.message
#
#try:
#    ret = vsmclient.vsm_settings.create(err2)
#except exceptions.BadRequest as e:
#    print e.message
try:
    ret = vsmclient.vsm_settings.get(name='fhweiofhweo')
    print ret
except exceptions.NotFound as e:
    print e.message