Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Group Perms update for argus client #34

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ dist
docs/_build
docs/README.rst
.idea/
venv/
9 changes: 9 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,15 @@ Look for an existing alert and delete it so that we can recreate it
logging.info("Deleting existing alert with name: %s id: %s", alert_name, alertobj.argus_id)
argus.alerts.delete(alertobj.argus_id)

Update and create groups and give permissions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

logging.info("Looking up existing group with groupID %s", groupID)
groupObj =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this required? Looks incomplete



Finally, create alert with a trigger and a notification
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Expand Down
4 changes: 2 additions & 2 deletions argusclient/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
# For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#

from .client import ArgusServiceClient, ArgusException, ArgusAuthException, ArgusObjectNotFoundException, MetricQuery, AnnotationQuery
from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, User, AddListResult
from .client import ArgusServiceClient, GroupPermissionsServiceClient, ArgusException, ArgusAuthException, ArgusObjectNotFoundException, MetricQuery, AnnotationQuery
from .model import Namespace, Metric, Annotation, GroupPermission, Dashboard, Alert, Trigger, Notification, User, AddListResult
209 changes: 161 additions & 48 deletions argusclient/client.py

Large diffs are not rendered by default.

23 changes: 21 additions & 2 deletions argusclient/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,29 @@ class Permission(BaseEncodable):
id_fields = ("type",)
VALID_TYPES = frozenset(("user", "group"))


def __init__(self, type, **kwargs):
assert type in Permission.VALID_TYPES, "Permission type %s is not valid" % type
assert type in Permission.VALID_TYPES, "permission type is not valid: %s" % type
super(Permission, self).__init__(type=type, **kwargs)

class GroupPermission(BaseEncodable):
"""
Represents a Group permission object in Argus

:param groupId : the id of the group to be given permissions to
:type groupId: str
:type grouppermissionIds: List of permissions that this group
has on the associated entity (id is put in the entityId field).
Permissions in this list are in the form of integers: like 0, 1, and 2.
0, 1, and 2 correspond to "VIEW", "EDIT", and "DELETE" respectively.
"""

id_fields = ("groupId","permissionIds")

def __init__(self, groupId,permissionIds, **kwargs):
super(GroupPermission, self).__init__( permissionId = permissionIds, groupId=groupId,**kwargs)


class Namespace(BaseEncodable):
"""
Represents a Namespace object in Argus.
Expand Down Expand Up @@ -493,7 +512,7 @@ def __init__(self, *args, **kwargs):
def from_json(self, jsonObj):
if not jsonObj or not isinstance(jsonObj, dict):
return jsonObj
for cls in (Metric, Dashboard, AddListResult, User, Namespace, Annotation, Alert, Trigger, Notification, Permission):
for cls in (Metric, Dashboard, AddListResult, User, Namespace, Annotation, Alert, Trigger, Notification, Permission, GroupPermission):
obj = cls.from_dict(jsonObj)
if obj:
return obj
Expand Down
42 changes: 37 additions & 5 deletions tests/test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,26 @@
notificationName = "test.notification"
groupPermissionIdentifier = "group"
userPermissionIdentifier = "user"
groupID = "5eb1fc18-c985-47eb-94f9-aebce66e119a"
permissionNames = ["VIEW", "EDIT", "DELETE"]
permissionGroupId = '24231-52321-43523-64353-23111'
username = "testuser"
permission_ids = [1,2,3]
group_id = "c8be7819-bf5e-40aa-8535-88694d34280f"
entity_id = 23590046

username = "testuser"
permission_ids = [1,2,3]
user_type = "user"
group_type = "group"
group_id = "c8be7819-bf5e-40aa-8535-88694d34280f"
entity_id = 23590046

permissionGroup2ID= '24231-52321-43523-64353-23121'
permissionGroup3ID = '24231-52321-43523-64353-24121'
permissionGroupIdBad = '2423480-3843hlfw-jf'


compAlertID = 6000
childAlertID_1 = 6003
childAlertID_2 = 6009
Expand Down Expand Up @@ -121,10 +134,29 @@
}

groupPermission_D = {
"type": groupPermissionIdentifier,
"permissionNames": permissionNames,
"groupId": permissionGroupId
"type": "group",
"groupId": permissionGroupId,
"permissionIds": [0,1,2]
}
groupPermission_E = {
"type": "group",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could use the variable groupPermissionIdentifier here

"groupId": permissionGroup2ID,
"permissionIds": [0,1]
}

groupPermission_F = {
"type": "group",
"groupId": permissionGroup3ID,
"permissionIds": [0,1,2]
}


groupBadPermission_D = {
"groupId": groupID,
"permissionIds": [0,3]
}



userPermission_D = {
"type": userPermissionIdentifier,
Expand Down Expand Up @@ -372,7 +404,7 @@
'id': triggerID_1,
'threshold': 1.0,
'type': 'GREATER_THAN',
'inertia': 0L,
'inertia': 0,
'name': 'CompAlertTest/trigger1'
}

Expand All @@ -383,7 +415,7 @@
'subscriptions': ['[email protected]'],
'notifierName': 'com.salesforce.dva.argus.service.alert.notifier.EmailNotifier',
'metricsToAnnotate': [],
'cooldownPeriod': 0L,
'cooldownPeriod': 0,
'sractionable': False,
'customText': 'None'
}
119 changes: 119 additions & 0 deletions tests/test_group.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need to check this file in

# Copyright (c) 2016, salesforce.com, inc.
# All rights reserved.
# Licensed under the BSD 3-Clause license.
# For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
# Use the package in this repo (argusclient directory)

from argusclient import *
from argusclient.model import Permission

"""
LOGGING IN!~
"""
username = "s.basu"
password = ""
argus = ArgusServiceClient(user="s.basu",
password=password,
endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/")
# endpoint = "https://argus-ws.data.sfdc.net/argusws/")
print ('logging in...')
argus.login()
print ('logged in!')
"""
Set endpoint and params
"""
argus.grouppermissions = GroupPermissionsServiceClient(argus, get_all_req_opts= dict(groupID="234-567-891-667-001", type="group",
permissionsID=[0,1,2]))

print(argus.grouppermissions)
print(type(argus.grouppermissions))

# argus.alerts = AlertsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False,
# alertNameContains='TestAlert',
# limit=1),
# REQ_PATH: "allinfo"})
# permission_group_D = {
# "id": 10,
# "createdById": 6906380,
# "createdDate": 1616098911000,
# "modifiedById": 6906380,
# "modifiedDate": 1616098911000,
# "type": "group",
# "groupId": "c8be7819-bf5e-40aa-8535-88694d34280f",
# "username": '',
# "permissionIds": [],
# "entityId": 23590046
# }

GroupPermission_D = {
"type": "group",
"groupId": "ebd7db70-290b-4d85-b366-b4be9d5967e4",
"permissionIds": [0,1,2],
"permissionNames": []
}
GroupPermission_R ={
"type": "group",
"groupId": "ebd7db70-290b-4d85-b366-b4be9d5967e4",
"permissionIds": [1],
"permissionNames": []
}
groupID1 = "ebd7db70-290b-4d85-b366-b4be9d5967e4"
grouppermission = GroupPermission.from_dict(GroupPermission_D)
perm = Permission.from_dict(GroupPermission_R)
#groupPerm = argus.grouppermissions.get_permissions_for_group(groupID1)
#print("groupPerms are "+ str(groupPerm))
#grouppermission = GroupPermission(GroupPermission_D.get("groupId"),[0,1,2])
groupPerm1 = argus.grouppermissions.add_permissions_for_group(grouppermission)
print("groupPerms are "+ str(groupPerm1))

deletedPerm = argus.grouppermissions.delete_permissions_for_group(perm) #this is not working as adding group_permission returns a permission object instead of groupPermission object ?
print("removed groupPerms are "+ str(deletedPerm))

#argus.permissions = PermissionsServiceClient(argus)
#group_perm = Permission.from_dict(permission_group_D)
# delattr(group_perm, "id")
# deleted_perm = argus.permissions.delete(23590046, group_perm)
#
# print "updating perm"
# updated_perm = argus.permissions.add(23590046, group_perm)
# print "updated permission is "+ str(updated_perm)
#print ("making call to get perms for entities")
#all_perms = argus.permissions.get_permissions_for_entities([26947204])
#print (all_perms)
#print (type(group_perm))
#for id, val group_perm.items():
#print (id)
# print (type(val))
# for perm in val:
# perm_type = perm.type
# if perm_type == 'group':
## print (perm.groupId)
# else:
# print (perm.username)
# argus.permissions = PermissionsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False),
# # REQ_PATH: "entityIds",
# # REQ_METHOD: "post",
# # REQ_BODY: [14796957, 14796958]})
# argus.dashboards = DashboardsServiceClient(argus, get_all_req_opts=dict(REQ_PARAMS=dict(username="j.ma", shared=False, limit=3))) # note - limit does not work
"""
Making the call
"""
if __name__ == '__main__':

# print 'calling items()'
# res = argus.alerts.items()
# res = argus.permissions.items()
# res = argus.dashboards.items()
print ("calling groupPerms")
# res1 = groupPerm1

#print ('size of result: ', len())
#res = argus.permissions.get(16348603)
# Get notif
# alert = res[0][1]
# print 'notifs:', alert.notifications.items()
# notifs = alert.notifications.items()
# notif = notifs[0][1]
# print '\nresult: ', res
2 changes: 1 addition & 1 deletion tests/test_modelobjs.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def testEncUserPermission(self):
self._testFor(userPermission_D, Permission)

def testEncGroupPermission(self):
self._testFor(groupPermission_D, Permission)
self._testFor(groupPermission_D, GroupPermission)

def testEncNamespace(self):
self._testFor(namespace_D, Namespace)
Expand Down
32 changes: 29 additions & 3 deletions tests/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@
import unittest

from argusclient import *
from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, PermissionsServiceClient, \
from argusclient.client import JsonDecoder, check_success, AlertsServiceClient, PermissionsServiceClient, \
DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY
from argusclient.model import Permission

from test_data import *

try:
Expand Down Expand Up @@ -198,6 +197,9 @@ def testInvalidRefreshTokenWithDirectAccessToken(self):
self.assertEquals((os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"),), called_endpoints(mockConn.get))
self.assertEquals(3, mockConn.get.call_count)




def testInvalidPasswordWithDirectRefreshToken(self):
"""Test inability to refresh refresh token as there is no password"""
self.argus.refreshToken = "refresh"
Expand Down Expand Up @@ -390,6 +392,29 @@ def testGetItems(self, mockGet):
self.assertIn((os.path.join(endpoint, "dashboards"),), tuple(mockGet.call_args))
self.assertEquals(len(mockGet.call_args_list), 1)

class TestGroupPermissions(TestServiceBase):
@mock.patch('requests.Session.get', return_value=MockResponse(json.dumps(groupPermission_D), 200))
def testGroupPermissionsID(self, mockGet):
res = self.argus.grouppermissions.get_permissions_for_group(permissionGroupId)
self.assertEquals(res.get("permissionIds"), [0, 1, 2])
self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockGet.call_args))

@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupPermission_E), 200))
def testGroupPermissionsIDAdd(self, mockPost):
ggroupId = permissionGroup2ID
gperms = GroupPermission(ggroupId, [1])
res = self.argus.grouppermissions.add_permissions_for_group(gperms)
self.assertEquals(res.permissionIds, [0, 1])
self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args))


@mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(groupPermission_F), 200))
def testDeletePermission(self, mockDelete):
gpermission = Permission.from_dict(groupPermission_F) # group with new permissions
res = self.argus.grouppermissions.delete_permissions_for_group(gpermission)
self.assertEquals(res, False) #self._colls is empty
self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockDelete.call_args))


class TestPermission(TestServiceBase):
@mock.patch('requests.Session.post', return_value=MockResponse({}, 200))
Expand All @@ -402,6 +427,7 @@ def testGetPermissionsBadId(self, mockPost):
testId2: [userPermission_D],
testId3: []}), 200))
def testGetItems(self, mockPost):

# Check
self.assertEquals(len(mockPost.call_args_list), 0)

Expand Down Expand Up @@ -440,7 +466,7 @@ def testGetItems(self, mockPost):
@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D, groupPermission_D],
testId2: [userPermission_D],
testId3: []}), 200))
def testGetPermissions(self, mockPost):
def testGetPermissions(self, mockPost): #test is broken in master as well
resp = self.argus.permissions.get_permissions_for_entities([testId, testId2, testId3])
for id, perms in resp.items():
for p in perms:
Expand Down