Ejemplo n.º 1
0
def regenerate_api_key(geniuser):
  """
  <Purpose>
    Regenerates the user's API key.
  <Arguments>
    geniuser
      A GeniUser object of the user whose api key is to be regenerated.
  <Exceptions>
    None
  <Side Effects>
    The API key for the user is updated in the database.
  <Returns>
    The new API key.
  """
  assert_geniuser(geniuser)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect changes we make to the object.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    return maindb.regenerate_api_key(geniuser)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle) 
Ejemplo n.º 2
0
def regenerate_api_key(geniuser):
  """
  <Purpose>
    Regenerates the user's API key.
  <Arguments>
    geniuser
      A GeniUser object of the user whose api key is to be regenerated.
  <Exceptions>
    None
  <Side Effects>
    The API key for the user is updated in the database.
  <Returns>
    The new API key.
  """
  assert_geniuser(geniuser)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect changes we make to the object.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    return maindb.regenerate_api_key(geniuser)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle) 
Ejemplo n.º 3
0
def change_user_keys(geniuser, pubkey=None):
  """
  <Purpose>
    Sets a new public/private key for the user and initiates the change
    of user keys on all vessels the user has access to. If pubkey is
    provided, that is used as the user's new pubkey. If pubkey is not
    provided, a new public/private keypair is generated for the user.
  <Arguments>
    geniuser
      A GeniUser object of the user whose keys are to be updated.
  <Exceptions>
    ValidationError
      If the pubkey is provided and is invalid.
  <Side Effects>
    The public and private keys of the user are replaced in the database with
    new keys (if pubkey was provided, the private key in the database will
    be empty, otherwise it will be the generated private key). All vessels the
    user has access to are marked as needing to have their user keys sync'd.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  
  if pubkey is not None:
    validations.validate_pubkey_string(pubkey)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect changes we make to the object.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Get a key pair from the keygen api if the user didn't supply their own pubkey.
    if pubkey is None:
      (pubkey, privkey) = keygen.generate_keypair()
    else:
      privkey = None    
    
    maindb.set_user_keys(geniuser, pubkey, privkey)
    
    # Now we need to find all of the vessels the user has access to and set
    # them to have their user keys updated by the backend.
    vessel_list = maindb.get_vessels_accessible_by_user(geniuser)
    if vessel_list:
      vessels.flag_vessels_for_user_keys_sync(lockserver_handle, vessel_list)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 4
0
def change_user_keys(geniuser, pubkey=None):
  """
  <Purpose>
    Sets a new public/private key for the user and initiates the change
    of user keys on all vessels the user has access to. If pubkey is
    provided, that is used as the user's new pubkey. If pubkey is not
    provided, a new public/private keypair is generated for the user.
  <Arguments>
    geniuser
      A GeniUser object of the user whose keys are to be updated.
  <Exceptions>
    ValidationError
      If the pubkey is provided and is invalid.
  <Side Effects>
    The public and private keys of the user are replaced in the database with
    new keys (if pubkey was provided, the private key in the database will
    be empty, otherwise it will be the generated private key). All vessels the
    user has access to are marked as needing to have their user keys sync'd.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  
  if pubkey is not None:
    validations.validate_pubkey_string(pubkey)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect changes we make to the object.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Get a key pair from the keygen api if the user didn't supply their own pubkey.
    if pubkey is None:
      (pubkey, privkey) = keygen.generate_keypair()
    else:
      privkey = None    
    
    maindb.set_user_keys(geniuser, pubkey, privkey)
    
    # Now we need to find all of the vessels the user has access to and set
    # them to have their user keys updated by the backend.
    vessel_list = maindb.get_vessels_accessible_by_user(geniuser)
    if vessel_list:
      vessels.flag_vessels_for_user_keys_sync(lockserver_handle, vessel_list)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
def setup_movingto_canonical_to_onepercent():
  """
  <Purpose>
    Setup everything thats needed to run the 
    movingto_canonical_to_onepercent test.

  <Arguments>
    None.

  <Side Effects>
    None.

  <Return>
    None.
  """

  testuser = maindb.get_user(mockutil.testusername)

  # Retrieve the info about the donation we just made.
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  # Delete all the vessel records from the database. Assume that the nodes were
  # joined back by this point.
  maindb.delete_all_vessels_of_node(node)

  # Do the setup for this test.
  vessels_dict[mockutil.extra_vessel_name]['userkeys'] = [node_transition_lib.transition_state_keys['movingto_canonical']]
  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)
  mockutil.mock_backend_split_vessel()
  mockutil.mock_backend_set_vessel_user_keylist([mockutil._mock_pubkey_to_string(
                                                node_transition_lib.transition_state_keys['onepercentmanyevents'])])
Ejemplo n.º 6
0
def run_moving2onepercent_to_canonical_test():

  transitionlist = []


  # Change the vessel_dict and reset all the mock functions in order to have the appropriate info
  testuser = maindb.get_user(mockutil.testusername)

  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  # Create 9 vessels for this node
  for i in range(9):
    vessels_dict["vessel"+str(i)]={}
    vessels_dict["vessel"+str(i)]["userkeys"] = []
    vessels_dict["vessel"+str(i)]["ownerkey"] = rsa_string_to_publickey(node.owner_pubkey)
    vessels_dict["vessel"+str(i)]["ownerinfo"] = ""
    vessels_dict["vessel"+str(i)]["status"] = ""
    vessels_dict["vessel"+str(i)]["advertise"] = True

    maindb.create_vessel(node, "vessel"+str(i))



  vessels_dict[mockutil.extra_vessel_name]["userkeys"] = [node_transition_lib.transition_state_keys['movingto_onepercentmanyevents']]
  vessels_dict[mockutil.extra_vessel_name]["ownerkey"] = rsa_string_to_publickey(node.owner_pubkey)

  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)
  mockutil.mock_backend_set_vessel_owner_key()
  mockutil.mock_backend_join_vessels()
  mockutil.mock_backend_set_vessel_user_keylist([mockutil._mock_pubkey_to_string(
                                                node_transition_lib.transition_state_keys['canonical'])])


  transitionlist.append(("movingto_onepercentmanyevents", "canonical",
                         node_transition_lib.combine_vessels,
                         node_transition_lib.noop, False))

  print "Starting canonical to movingtoonepercentmanyevents test....."

  (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

  assert(success_count == 1)
  assert(failure_count == 0)

  assert_database_info_before_completed()

  assert(mockutil.set_vessel_owner_key_call_count == 0)

  assert(mockutil.set_vessel_user_keylist_call_count == 1)

  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node
  
  vessel_list_per_node = maindb.get_vessels_on_node(node)

  #testing to see if the vessels were deleted after join_vessels was called
  assert(mockutil.join_vessels_call_count == 9)
  assert(len(vessel_list_per_node) == 0)
  assert(node.extra_vessel_name == "extra_vessel_join9")
def setup_movingto_canonical_to_onepercent():
  """
  <Purpose>
    Setup everything thats needed to run the 
    movingto_canonical_to_onepercent test.

  <Arguments>
    None.

  <Side Effects>
    None.

  <Return>
    None.
  """

  testuser = maindb.get_user(mockutil.testusername)

  # Retrieve the info about the donation we just made.
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  # Delete all the vessel records from the database. Assume that the nodes were
  # joined back by this point.
  maindb.delete_all_vessels_of_node(node)

  # Do the setup for this test.
  vessels_dict[mockutil.extra_vessel_name]['userkeys'] = [node_transition_lib.transition_state_keys['movingto_canonical']]
  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)
  mockutil.mock_backend_split_vessel()
  mockutil.mock_backend_set_vessel_user_keylist([mockutil._mock_pubkey_to_string(
                                                node_transition_lib.transition_state_keys['onepercentmanyevents'])])
Ejemplo n.º 8
0
def run_moving2onepercent_to_onepercent_test():

  transitionlist = []


  # Change the vessel_dict and reset all the mock functions in order to have the appropriate info
  vessels_dict[mockutil.extra_vessel_name]["userkeys"] = [node_transition_lib.movingtoonepercentmanyeventspublickey]  

  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)
  mockutil.mock_backend_set_vessel_owner_key()
  mockutil.mock_backend_split_vessel()
  mockutil.mock_backend_set_vessel_user_keylist([mockutil._mock_pubkey_to_string(
                                                node_transition_lib.onepercentmanyeventspublickey)])

  onepercentmanyevents_resource_fd = file(transition_canonical_to_onepercentmanyevents.RESOURCES_TEMPLATE_FILE_PATH)
  onepercentmanyevents_resourcetemplate = onepercentmanyevents_resource_fd.read()
  onepercentmanyevents_resource_fd.close()

  


  transitionlist.append((("movingto_onepercent_state", node_transition_lib.movingtoonepercentmanyeventspublickey),
                        ("onepercentmanyevents_state", node_transition_lib.onepercentmanyeventspublickey),
                         transition_canonical_to_onepercentmanyevents.onepercentmanyevents_divide,
                         node_transition_lib.noop,
                         onepercentmanyevents_resourcetemplate))

  print "Starting canonical to movingtoonepercentmanyevents test....."

  (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

  assert(success_count == 1)
  assert(failure_count == 0)

  assert_database_info_after_completed()

  assert(mockutil.set_vessel_owner_key_call_count == 0)
  
  # Note that the call to set_vessel_user_keylist should be 10.
  # 9 time for splitting the vessels and setting keylist to []
  # and one time for setting the actual state of the node.
  assert(mockutil.set_vessel_user_keylist_call_count == 10)

  testuser = maindb.get_user(mockutil.testusername)

  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  vessel_list_per_node = maindb.get_vessels_on_node(node)

  #testing to see if the vessels exist after splitting
  assert(mockutil.split_vessel_call_count == 9)
  assert(len(vessel_list_per_node) == 9)

  for i in range(len(vessel_list_per_node)):
    # Note that the vessel names go from 1-9 rather then 0-8
    assert(vessel_list_per_node[i].node == node)
    assert(vessel_list_per_node[i].name == "new_vessel"+str(1+i))

  assert(node.extra_vessel_name == "extra_vessel_split9")
def run_movingto_twopercent_to_canonical_test():

  transitionlist = []


  # Change the vessel_dict and reset all the mock functions in order to have the appropriate info
  testuser = maindb.get_user(mockutil.testusername)

  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  # Create 9 vessels for this node
  for i in range(9):
    vessels_dict["vessel"+str(i)]={}
    vessels_dict["vessel"+str(i)]["userkeys"] = []
    vessels_dict["vessel"+str(i)]["ownerkey"] = rsa_string_to_publickey(node.owner_pubkey)
    vessels_dict["vessel"+str(i)]["ownerinfo"] = ""
    vessels_dict["vessel"+str(i)]["status"] = ""
    vessels_dict["vessel"+str(i)]["advertise"] = True

    maindb.create_vessel(node, "vessel"+str(i))



  vessels_dict[mockutil.extra_vessel_name]["userkeys"] = [node_transition_lib.transition_state_keys['movingto_twopercent']]
  vessels_dict[mockutil.extra_vessel_name]["ownerkey"] = rsa_string_to_publickey(node.owner_pubkey)

  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)
  mockutil.mock_backend_set_vessel_owner_key()
  mockutil.mock_backend_join_vessels()
  mockutil.mock_backend_set_vessel_user_keylist([mockutil._mock_pubkey_to_string(
                                                node_transition_lib.transition_state_keys['canonical'])])


  transitionlist.append(("movingto_twopercent", "canonical",
                         node_transition_lib.combine_vessels,
                         node_transition_lib.noop, False))

  print "Starting movingto_twopercent to canonical test....."

  (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

  assert(success_count == 1)
  assert(failure_count == 0)

  assert_database_info_before_completed()

  assert(mockutil.set_vessel_owner_key_call_count == 0)

  assert(mockutil.set_vessel_user_keylist_call_count == 1)

  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node
  
  vessel_list_per_node = maindb.get_vessels_on_node(node)

  #testing to see if the vessels were deleted after join_vessels was called
  assert(mockutil.join_vessels_call_count == 9)
  assert(len(vessel_list_per_node) == 0)
  assert(node.extra_vessel_name == "extra_vessel_join9")
Ejemplo n.º 10
0
def run_database_stituation_three_test():
    """
  <Purpose>
    The purpose of this test is to test the case where a record
    for the node has been registered in the database and a 
    record for the donation has been registered, but the
    owner key on the node has not been changed.

  <Arguments>
    None

  <Exceptions>
    None

  <Side Effects>
    None

  <Return>
    None
  """

    # Create a database entry for the node
    node_object = maindb.create_node(
        mockutil.nodeid_key_str,
        mockutil.node_ip,
        mockutil.node_port,
        "10.0test",
        False,
        mockutil.per_node_key_str,
        mockutil.extra_vessel_name,
    )

    user_object = maindb.get_user(mockutil.testusername)

    # Create a donation for user
    maindb.create_donation(node_object, user_object, "Making a donation")

    transitionlist = []

    transitionlist.append(
        (
            ("donation_state", node_transition_lib.acceptdonationpublickey),
            ("canonical_state", node_transition_lib.canonicalpublickey),
            node_transition_lib.noop,
            node_transition_lib.noop,
        )
    )

    print "Running test where database has record of node, has record of donation and node has donor key"

    (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

    assert success_count == 1
    assert failure_count == 0

    assert_database_info()

    assert mockutil.set_vessel_owner_key_call_count == 1
    assert mockutil.set_vessel_user_keylist_call_count == 1
def ban_user_and_remove_vessels(username):

    try:
        geniuser = maindb.get_user(username, allow_inactive=True)
    except DoesNotExistError:
        print "No such user: %s." % username
        sys.exit(1)

    # Lock the user.
    lockserver_handle = lockserver.create_lockserver_handle()
    lockserver.lock_user(lockserver_handle, geniuser.username)

    try:
        if geniuser.is_active:
            geniuser.is_active = False
            geniuser.save()
            print "This account has been set to inactive (banned)."
        else:
            print "This account is already inactive (banned)."

        acquired_vessels = maindb.get_acquired_vessels(geniuser)
        if not acquired_vessels:
            print "No acquired vessels to stop/remove access to."
        else:
            print "Vessels acquired by this user: %s" % acquired_vessels
            print "Indicating to the backend to release %s vessels." % len(
                acquired_vessels)
            vessels.release_vessels(lockserver_handle, geniuser,
                                    acquired_vessels)
            print "Release indicated. Monitoring db to see if the backend cleaned them up."
            while True:
                for vessel in acquired_vessels[:]:
                    updated_vessel = maindb.get_vessel(
                        vessel.node.node_identifier, vessel.name)
                    if vessel.node.is_broken or not vessel.node.is_active:
                        print "Node %s is broken or inactive, so backend won't contact it." % vessel.node
                        acquired_vessels.remove(vessel)
                        continue

                    if updated_vessel.is_dirty:
                        print "Vessel %s has not been cleaned up yet." % updated_vessel
                    else:
                        print "Vessel %s has been cleaned up." % updated_vessel
                        acquired_vessels.remove(vessel)

                if not acquired_vessels:
                    print "All vessels have been cleaned up."
                    break
                else:
                    print "%s vessels remain to be cleaned up." % len(
                        acquired_vessels)

                print "Sleeping 10 seconds."
                time.sleep(10)

    finally:
        # Unlock the user.
        lockserver.unlock_user(lockserver_handle, geniuser.username)
        lockserver.destroy_lockserver_handle(lockserver_handle)
  def test_regenerate_user_key(self):
    
    pubkey = "1 2"
    privkey = "3 4 5"
    donor_key = "6 7"
    
    # Create a user who will be doing the acquiring.
    user = maindb.create_user("testuser", "password", "*****@*****.**", "affiliation", 
                              pubkey, privkey, donor_key)
    userport = user.usable_vessel_port

    vesselcount = 4
    
    # Have every vessel acquisition to the backend request succeed.
    calls_results = [True] * vesselcount
    mocklib.mock_backend_acquire_vessel(calls_results)
    
    testutil.create_nodes_on_different_subnets(vesselcount, [userport])

    # Acquire all vessels on behalf of this user.
    all_vessels_list = interface.acquire_vessels(user, vesselcount, 'rand')

    # Release 2 vessels.
    released_vessels_list = all_vessels_list[:2]
    kept_vessels_list = all_vessels_list[2:]
    interface.release_vessels(user, released_vessels_list)
    
    # Ensure all of the vessels are marked as having user keys in sync.
    for vessel in all_vessels_list:
      # Get a fresh vessel from the db.
      vessel = maindb.get_vessel(vessel.node.node_identifier, vessel.name)
      self.assertTrue(vessel.user_keys_in_sync)

    # We expect a single key to be generated through the keygen api (the new
    # user public key).
    mocklib.mock_keygen_generate_keypair([("55 66", "77 88 99")])
    
    interface.change_user_keys(user, pubkey=None)
    
    # Get a new user object from the database.
    user = maindb.get_user(user.username)
    
    # Make sure the user's key changed.
    self.assertEqual(user.user_pubkey, "55 66")
    self.assertEqual(user.user_privkey, "77 88 99")
    
    # Make sure that all of the vessels the user has access to (and no other
    # vessels) are marked as needing user keys to be sync'd.
    # Ensure all of the vessels are marked as having user keys in sync.
    for vessel in kept_vessels_list:
      # Get a fresh vessel from the db.
      vessel = maindb.get_vessel(vessel.node.node_identifier, vessel.name)
      self.assertFalse(vessel.user_keys_in_sync)

    for vessel in released_vessels_list:
      # Get a fresh vessel from the db.
      vessel = maindb.get_vessel(vessel.node.node_identifier, vessel.name)
      self.assertTrue(vessel.user_keys_in_sync)
Ejemplo n.º 13
0
def renew_vessels(geniuser, vessel_list):
  """
  <Purpose>
    Extend the expiration dates of vessels acquired by a user.
  <Arguments>
    geniuser
      The GeniUser whose vessels are to be renewed.
    vessel_list
      A list of vessels to be renewed.
  <Exceptions>
    InvalidRequestError
      If any of the vessels in the vessel_list are not currently acquired by
      geniuser or if the list of vessels is empty.
    InsufficientUserResourcesError
      If the user is currently over their limit of acquired resources.
  <Side Effects>
    The vessels are renewed to the maximum time vessels can be acquired for,
    regardless of their previous individual expiration times.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  assert_list(vessel_list)
  for vessel in vessel_list:
    assert_vessel(vessel)

  if not vessel_list:
    raise InvalidRequestError("The list of vessels cannot be empty.")

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Ensure the user is not over their limit of acquired vessels due to
    # donations of theirs having gone offline. This call will raise an
    # InsufficientUserResourcesError if the user is currently over their
    # limit.
    vesselcount = 0
    maindb.require_user_can_acquire_resources(geniuser, vesselcount)
    
    # The vessels.renew_vessels function is responsible for ensuring that the
    # vessels belong to this user. We let the other function do the check
    # because we want to hold locks on the vessels' nodes before checking.
    vessels.renew_vessels(lockserver_handle, geniuser, vessel_list)

  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 14
0
def renew_vessels(geniuser, vessel_list):
  """
  <Purpose>
    Extend the expiration dates of vessels acquired by a user.
  <Arguments>
    geniuser
      The GeniUser whose vessels are to be renewed.
    vessel_list
      A list of vessels to be renewed.
  <Exceptions>
    InvalidRequestError
      If any of the vessels in the vessel_list are not currently acquired by
      geniuser or if the list of vessels is empty.
    InsufficientUserResourcesError
      If the user is currently over their limit of acquired resources.
  <Side Effects>
    The vessels are renewed to the maximum time vessels can be acquired for,
    regardless of their previous individual expiration times.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  assert_list(vessel_list)
  for vessel in vessel_list:
    assert_vessel(vessel)

  if not vessel_list:
    raise InvalidRequestError("The list of vessels cannot be empty.")

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Ensure the user is not over their limit of acquired vessels due to
    # donations of theirs having gone offline. This call will raise an
    # InsufficientUserResourcesError if the user is currently over their
    # limit.
    vesselcount = 0
    maindb.require_user_can_acquire_resources(geniuser, vesselcount)
    
    # The vessels.renew_vessels function is responsible for ensuring that the
    # vessels belong to this user. We let the other function do the check
    # because we want to hold locks on the vessels' nodes before checking.
    vessels.renew_vessels(lockserver_handle, geniuser, vessel_list)

  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 15
0
def ban_user_and_remove_vessels(username):

  try:
    geniuser = maindb.get_user(username, allow_inactive=True)
  except DoesNotExistError:
    print "No such user: %s." % username
    sys.exit(1)

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)

  try:
    if geniuser.is_active:
      geniuser.is_active = False
      geniuser.save()
      print "This account has been set to inactive (banned)."
    else:
      print "This account is already inactive (banned)."

    acquired_vessels = maindb.get_acquired_vessels(geniuser)
    if not acquired_vessels:
      print "No acquired vessels to stop/remove access to."
    else:
      print "Vessels acquired by this user: %s" % acquired_vessels
      print "Indicating to the backend to release %s vessels." % len(acquired_vessels)
      vessels.release_vessels(lockserver_handle, geniuser, acquired_vessels)
      print "Release indicated. Monitoring db to see if the backend cleaned them up."
      while True:
        for vessel in acquired_vessels[:]:
          updated_vessel = maindb.get_vessel(vessel.node.node_identifier, vessel.name)
          if vessel.node.is_broken or not vessel.node.is_active:
            print "Node %s is broken or inactive, so backend won't contact it." % vessel.node
            acquired_vessels.remove(vessel)
            continue

          if updated_vessel.is_dirty:
            print "Vessel %s has not been cleaned up yet." % updated_vessel
          else:
            print "Vessel %s has been cleaned up." % updated_vessel
            acquired_vessels.remove(vessel)

        if not acquired_vessels:
          print "All vessels have been cleaned up."
          break
        else:
          print "%s vessels remain to be cleaned up." % len(acquired_vessels)

        print "Sleeping 10 seconds."
        time.sleep(10)

  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 16
0
def change_user_affiliation(geniuser, new_affiliation):
  """
  <Purpose>
     Sets a new affiliation for the user 
  <Arguments>
    geniuser
      A GeniUser object of the user whose affiliation is to be updated.
    new_affiliation
      the new affiliation value
  <Exceptions>
    ValidationError
      If the affiliation is provided and is invalid.
  <Side Effects>
    The geniuser affiliation gets changed to the new value(in the db).
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  #Determines if the new affiliation is valid.  The frontend should already
  #checks for this but we validate again here just in case.
  validations.validate_affiliation(new_affiliation)
 
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect changes we make to the object.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())

    maindb.set_user_affiliation(geniuser, new_affiliation)
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 17
0
def acquire_specific_vessels(geniuser, vessel_list):
  """
  <Purpose>
    Attempt to acquire specific vessels for a user.
  <Arguments>
    geniuser
      The GeniUser which will be assigned the vessels.
    vessel_list
      A list of vessels to be acquired for the user.
  <Exceptions>
    InsufficientUserResourcesError
      The user does not have enough vessel credits to acquire the number of
      vessels requested.
    InvalidRequestError
      If the list of vessels is empty.
  <Side Effects>
    Zero or more of the vessels in vessel_list have been acquired by the user.
  <Returns>
    A list of the vessels acquired as a result of this function call. The
    length of this list may be less than the length of vessel_list if one or
    more of the vessels in vessel_list could not be acquired.
  """
  assert_geniuser(geniuser)
  assert_list(vessel_list)
  for vessel in vessel_list:
    assert_vessel(vessel)

  if not vessel_list:
    raise InvalidRequestError("The list of vessels cannot be empty.")

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Ensure the user is allowed to acquire these resources. This call will
    # raise an InsufficientUserResourcesError if the additional vessels would
    # cause the user to be over their limit.
    maindb.require_user_can_acquire_resources(geniuser, len(vessel_list))
    
    return vessels.acquire_specific_vessels_best_effort(lockserver_handle, geniuser, vessel_list)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 18
0
def acquire_specific_vessels(geniuser, vessel_list):
  """
  <Purpose>
    Attempt to acquire specific vessels for a user.
  <Arguments>
    geniuser
      The GeniUser which will be assigned the vessels.
    vessel_list
      A list of vessels to be acquired for the user.
  <Exceptions>
    InsufficientUserResourcesError
      The user does not have enough vessel credits to acquire the number of
      vessels requested.
    InvalidRequestError
      If the list of vessels is empty.
  <Side Effects>
    Zero or more of the vessels in vessel_list have been acquired by the user.
  <Returns>
    A list of the vessels acquired as a result of this function call. The
    length of this list may be less than the length of vessel_list if one or
    more of the vessels in vessel_list could not be acquired.
  """
  assert_geniuser(geniuser)
  assert_list(vessel_list)
  for vessel in vessel_list:
    assert_vessel(vessel)

  if not vessel_list:
    raise InvalidRequestError("The list of vessels cannot be empty.")

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Ensure the user is allowed to acquire these resources. This call will
    # raise an InsufficientUserResourcesError if the additional vessels would
    # cause the user to be over their limit.
    maindb.require_user_can_acquire_resources(geniuser, len(vessel_list))
    
    return vessels.acquire_specific_vessels_best_effort(lockserver_handle, geniuser, vessel_list)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
def run_database_stituation_three_test():
    """
  <Purpose>
    The purpose of this test is to test the case where a record
    for the node has been registered in the database and a 
    record for the donation has been registered, but the
    owner key on the node has not been changed.

  <Arguments>
    None

  <Exceptions>
    None

  <Side Effects>
    None

  <Return>
    None
  """

    # Create a database entry for the node
    node_object = maindb.create_node(mockutil.nodeid_key_str, mockutil.node_ip,
                                     mockutil.node_port, "10.0test", False,
                                     mockutil.per_node_key_str,
                                     mockutil.extra_vessel_name)

    user_object = maindb.get_user(mockutil.testusername)

    # Create a donation for user
    maindb.create_donation(node_object, user_object, "Making a donation")

    transitionlist = []

    transitionlist.append(
        (("donation_state", node_transition_lib.acceptdonationpublickey),
         ("canonical_state", node_transition_lib.canonicalpublickey),
         node_transition_lib.noop, node_transition_lib.noop))

    print "Running test where database has record of node, has record of donation and node has donor key"

    (success_count,
     failure_count) = node_transition_lib.do_one_processnode_run(
         transitionlist, "startstatename", 1)[0]

    assert (success_count == 1)
    assert (failure_count == 0)

    assert_database_info()

    assert (mockutil.set_vessel_owner_key_call_count == 1)
    assert (mockutil.set_vessel_user_keylist_call_count == 1)
def run_movingto_canonical_to_canonical():
    """
  <Purpose>
    Test the process of transitioning a node from the
    movingto_canonical state to the canonical
    state.

  <Arguments>
    None

  <Side Effects>
    None

  <Exceptions>
    AssertionError raised if test fails.

  <Return>
    None
  """

    print "Starting movingto_canonical to canonical test....."
    transitionlist = []

    transitionlist.append(
        ("movingto_canonical", "canonical",
         node_transition_lib.combine_vessels, node_transition_lib.noop, False))

    (success_count,
     failure_count) = node_transition_lib.do_one_processnode_run(
         transitionlist, "startstatename", 1)[0]

    assert (success_count == 1)
    assert (failure_count == 0)

    assert_database_info_non_active()

    assert (mockutil.set_vessel_owner_key_call_count == 0)
    assert (mockutil.set_vessel_user_keylist_call_count == 1)

    # Retrieve the donated node and check its status with the database.
    testuser = maindb.get_user(mockutil.testusername)
    all_donations = maindb.get_donations_by_user(
        testuser, include_inactive_and_broken=True)
    node = all_donations[0].node

    vessel_list_per_node = maindb.get_vessels_on_node(node)

    #testing to see if the vessels were deleted after join_vessels was called
    assert (mockutil.join_vessels_call_count == 9)
    assert (len(vessel_list_per_node) == 0)
    assert (node.extra_vessel_name == "extra_vessel_join9")
Ejemplo n.º 21
0
def delete_private_key(geniuser):
  """
  <Purpose>
    Deletes the private key of the specified user.
  <Arguments>
    geniuser
      A GeniUser object of the user whose private key is to be deleted.
  <Exceptions>
    None
  <Side Effects>
    The private key belonging to the user is deleted if it exists, otherwise
    the user account is not modified.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect the deletion of the key.
    # That is, we want the object passed in to have the user_privkey be None
    # when this function returns.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    maindb.delete_user_private_key(geniuser)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 22
0
def delete_private_key(geniuser):
  """
  <Purpose>
    Deletes the private key of the specified user.
  <Arguments>
    geniuser
      A GeniUser object of the user whose private key is to be deleted.
  <Exceptions>
    None
  <Side Effects>
    The private key belonging to the user is deleted if it exists, otherwise
    the user account is not modified.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect the deletion of the key.
    # That is, we want the object passed in to have the user_privkey be None
    # when this function returns.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    maindb.delete_user_private_key(geniuser)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
def run_movingto_canonical_to_canonical():
  """
  <Purpose>
    Test the process of transitioning a node from the
    movingto_canonical state to the canonical
    state.

  <Arguments>
    None

  <Side Effects>
    None

  <Exceptions>
    AssertionError raised if test fails.

  <Return>
    None
  """

  print "Starting movingto_canonical to canonical test....."
  transitionlist = []

  transitionlist.append(("movingto_canonical", "canonical",
                         node_transition_lib.combine_vessels,
                         node_transition_lib.noop, False))



  (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

  assert(success_count == 1)
  assert(failure_count == 0)

  assert_database_info_non_active()

  assert(mockutil.set_vessel_owner_key_call_count == 0)
  assert(mockutil.set_vessel_user_keylist_call_count == 1)

  # Retrieve the donated node and check its status with the database.
  testuser = maindb.get_user(mockutil.testusername)
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  vessel_list_per_node = maindb.get_vessels_on_node(node)

  #testing to see if the vessels were deleted after join_vessels was called
  assert(mockutil.join_vessels_call_count == 9)
  assert(len(vessel_list_per_node) == 0)
  assert(node.extra_vessel_name == "extra_vessel_join9")
Ejemplo n.º 24
0
def change_user_port(geniuser, new_port):
  """
  <Purpose>
     Sets a new port for the user 
  <Arguments>
    geniuser
      A GeniUser object of the user whose port is to be changed.
    new_port
      the new port value
  <Exceptions>
    ValidationError
      If the port is provided and it is not in the allowed range.
  <Side Effects>
    the geniuser port gets changed to the new value(in the db).
  <Returns>
    None
  """
  assert_geniuser(geniuser)

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    # We don't use the user object we retrieve because we want the
    # object passed in to the function to reflect changes we make to the object.
    try:
      maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())

    maindb.set_user_port(geniuser, new_port)
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 25
0
 def _create_user_expect_success(self, username, password=good_password, email=good_email, 
                                 affiliation=good_affiliation, pubkey=good_pubkey):
   
   # We expect a single key to be generated through the backed (the donor key)
   mocklib.mock_backend_generate_key(["1 2"])
   
   created_user = interface.register_user(username, password, email, affiliation, pubkey)
 
   user_from_db = maindb.get_user(username)
   assert(user_from_db.username == created_user.username)
   assert(user_from_db.email == created_user.email)
   assert(user_from_db.affiliation == created_user.affiliation)
   assert(user_from_db.user_pubkey == created_user.user_pubkey)
   assert(user_from_db.user_privkey == created_user.user_privkey)
   assert(user_from_db.donor_pubkey == created_user.donor_pubkey)
def assert_database_info():

    active_nodes_list = maindb.get_active_nodes()

    assert len(active_nodes_list) == 1
    assert active_nodes_list[0].node_identifier == mockutil.nodeid_key_str
    assert active_nodes_list[0].last_known_ip == mockutil.node_ip
    assert active_nodes_list[0].last_known_port == mockutil.node_port
    assert active_nodes_list[0].extra_vessel_name == mockutil.extra_vessel_name
    assert active_nodes_list[0].owner_pubkey == mockutil.per_node_key_str

    testuser = maindb.get_user(mockutil.testusername)
    donations_list = maindb.get_donations_by_user(testuser)

    assert len(donations_list) == 1
    assert donations_list[0].node == active_nodes_list[0]
def assert_database_info_after_completed():

  active_nodes_list = maindb.get_active_nodes()

  assert(len(active_nodes_list) == 1)
  assert(active_nodes_list[0].node_identifier == mockutil.nodeid_key_str)
  assert(active_nodes_list[0].last_known_ip == mockutil.node_ip)
  assert(active_nodes_list[0].last_known_port == mockutil.node_port)
  assert(active_nodes_list[0].extra_vessel_name == mockutil.extra_vessel_name)
  assert(active_nodes_list[0].owner_pubkey == mockutil.per_node_key_str)

  testuser = maindb.get_user(mockutil.testusername)
  donations_list = maindb.get_donations_by_user(testuser)

  assert(len(donations_list) == 1)
  assert(donations_list[0].node == active_nodes_list[0])
Ejemplo n.º 28
0
def assert_database_info_after_completed():

  active_nodes_list = maindb.get_active_nodes()

  assert(len(active_nodes_list) == 1)
  assert(active_nodes_list[0].node_identifier == mockutil.nodeid_key_str)
  assert(active_nodes_list[0].last_known_ip == mockutil.node_ip)
  assert(active_nodes_list[0].last_known_port == mockutil.node_port)
  assert(active_nodes_list[0].extra_vessel_name == mockutil.extra_vessel_name)
  assert(active_nodes_list[0].owner_pubkey == mockutil.per_node_key_str)

  testuser = maindb.get_user(mockutil.testusername)
  donations_list = maindb.get_donations_by_user(testuser)

  assert(len(donations_list) == 1)
  assert(donations_list[0].node == active_nodes_list[0])
Ejemplo n.º 29
0
def release_vessels(geniuser, vessel_list):
  """
  <Purpose>
    Remove a user from a vessel that is assigned to the user.
  <Arguments>
    geniuser
      The GeniUser who is to be removed from the vessel.
    vessel_list
      A list of vessels the user is to be removed from.
  <Exceptions>
    InvalidRequestError
      If any of the vessels in the vessel_list are not currently acquired by
      geniuser or if the list of vessels is empty.
  <Side Effects>
    The vessel is no longer assigned to the user. If this was the last user
    assigned to the vessel, the vessel is freed.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  assert_list(vessel_list)
  for vessel in vessel_list:
    assert_vessel(vessel)

  if not vessel_list:
    raise InvalidRequestError("The list of vessels cannot be empty.")

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    vessels.release_vessels(lockserver_handle, geniuser, vessel_list)

  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 30
0
def release_vessels(geniuser, vessel_list):
  """
  <Purpose>
    Remove a user from a vessel that is assigned to the user.
  <Arguments>
    geniuser
      The GeniUser who is to be removed from the vessel.
    vessel_list
      A list of vessels the user is to be removed from.
  <Exceptions>
    InvalidRequestError
      If any of the vessels in the vessel_list are not currently acquired by
      geniuser or if the list of vessels is empty.
  <Side Effects>
    The vessel is no longer assigned to the user. If this was the last user
    assigned to the vessel, the vessel is freed.
  <Returns>
    None
  """
  assert_geniuser(geniuser)
  assert_list(vessel_list)
  for vessel in vessel_list:
    assert_vessel(vessel)

  if not vessel_list:
    raise InvalidRequestError("The list of vessels cannot be empty.")

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    vessels.release_vessels(lockserver_handle, geniuser, vessel_list)

  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
Ejemplo n.º 31
0
def get_user_without_password(username):
  """
  <Purpose>
    Gets the user record corresponding to the given username.
  <Arguments>
    username
      The username (must be a string).
  <Exceptions>
    DoesNotExistError
      If there is no user with the specified username.
  <Side Effects>
    None
  <Returns>
    The GeniUser instance if the username is valid.
  """
  assert_str(username)
  
  return maindb.get_user(username)
Ejemplo n.º 32
0
def get_user_without_password(username):
  """
  <Purpose>
    Gets the user record corresponding to the given username.
  <Arguments>
    username
      The username (must be a string).
  <Exceptions>
    DoesNotExistError
      If there is no user with the specified username.
  <Side Effects>
    None
  <Returns>
    The GeniUser instance if the username is valid.
  """
  assert_str(username)
  
  return maindb.get_user(username)
Ejemplo n.º 33
0
def get_user_for_installers(username):
  """
  <Purpose>
    Gets the user record corresponding to the given username.
    IMPORTANT: Used ONLY FOR getting the user object for downloading/building installers.
               Do NOT use for any other purpose, as this function does not validate passwords.
  <Arguments>
    username
      The username (must be a string).
  <Exceptions>
    DoesNotExistError
      If there is no user with the specified username and password.
  <Side Effects>
    None
  <Returns>
    The GeniUser instance if the username is valid.
  """
  assert_str(username)
  
  return maindb.get_user(username)
Ejemplo n.º 34
0
def get_user_for_installers(username):
  """
  <Purpose>
    Gets the user record corresponding to the given username.
    IMPORTANT: Used ONLY FOR getting the user object for downloading/building installers.
               Do NOT use for any other purpose, as this function does not validate passwords.
  <Arguments>
    username
      The username (must be a string).
  <Exceptions>
    DoesNotExistError
      If there is no user with the specified username and password.
  <Side Effects>
    None
  <Returns>
    The GeniUser instance if the username is valid.
  """
  assert_str(username)
  
  return maindb.get_user(username)
def assert_database_info_before_completed():

  active_nodes_list = maindb.get_active_nodes()
  assert(len(active_nodes_list) == 0)
  
  testuser = maindb.get_user(mockutil.testusername)
    
  active_donations = maindb.get_donations_by_user(testuser)
  assert(len(active_donations) == 0)
  
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  assert(len(all_donations) == 1)
  
  node = all_donations[0].node
  
  assert(node.node_identifier == mockutil.nodeid_key_str)
  assert(node.last_known_ip == mockutil.node_ip)
  assert(node.last_known_port == mockutil.node_port)
  assert(node.extra_vessel_name == mockutil.extra_vessel_name)
  assert(node.owner_pubkey == mockutil.per_node_key_str)
Ejemplo n.º 36
0
    def _create_user_expect_success(self,
                                    username,
                                    password=good_password,
                                    email=good_email,
                                    affiliation=good_affiliation,
                                    pubkey=good_pubkey):

        # We expect a single key to be generated through the backed (the donor key)
        mocklib.mock_backend_generate_key(["1 2"])

        created_user = interface.register_user(username, password, email,
                                               affiliation, pubkey)

        user_from_db = maindb.get_user(username)
        assert (user_from_db.username == created_user.username)
        assert (user_from_db.email == created_user.email)
        assert (user_from_db.affiliation == created_user.affiliation)
        assert (user_from_db.user_pubkey == created_user.user_pubkey)
        assert (user_from_db.user_privkey == created_user.user_privkey)
        assert (user_from_db.donor_pubkey == created_user.donor_pubkey)
Ejemplo n.º 37
0
def assert_database_info_before_completed():

  active_nodes_list = maindb.get_active_nodes()
  assert(len(active_nodes_list) == 0)
  
  testuser = maindb.get_user(mockutil.testusername)
    
  active_donations = maindb.get_donations_by_user(testuser)
  assert(len(active_donations) == 0)
  
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  assert(len(all_donations) == 1)
  
  node = all_donations[0].node
  
  assert(node.node_identifier == mockutil.nodeid_key_str)
  assert(node.last_known_ip == mockutil.node_ip)
  assert(node.last_known_port == mockutil.node_port)
  assert(node.extra_vessel_name == mockutil.extra_vessel_name)
  assert(node.owner_pubkey == mockutil.per_node_key_str)
Ejemplo n.º 38
0
  def test_seattlegeni_generates_user_keypair(self):
    
    # We expect a single keypair to be generated directly through the keygen
    # api (specifically, the user keys).
    user_pubkey = "3 4"
    user_privkey = "2 3 3"
    mocklib.mock_keygen_generate_keypair([(user_pubkey, user_privkey)])
    
    # We expect a single key to be generated directly through the backed api
    # (specifically, the donor key).
    donor_pubkey = "1 2"
    mocklib.mock_backend_generate_key([donor_pubkey])
    
    provided_pubkey=None
    interface.register_user(good_username, good_password, good_email, 
                                           good_affiliation, provided_pubkey)

    user_from_db = maindb.get_user(good_username)

    assert(user_from_db.user_pubkey == user_pubkey)
    assert(user_from_db.user_privkey == user_privkey)
    assert(user_from_db.donor_pubkey == donor_pubkey)
Ejemplo n.º 39
0
    def test_seattlegeni_generates_user_keypair(self):

        # We expect a single keypair to be generated directly through the keygen
        # api (specifically, the user keys).
        user_pubkey = "3 4"
        user_privkey = "2 3 3"
        mocklib.mock_keygen_generate_keypair([(user_pubkey, user_privkey)])

        # We expect a single key to be generated directly through the backed api
        # (specifically, the donor key).
        donor_pubkey = "1 2"
        mocklib.mock_backend_generate_key([donor_pubkey])

        provided_pubkey = None
        interface.register_user(good_username, good_password, good_email,
                                good_affiliation, provided_pubkey)

        user_from_db = maindb.get_user(good_username)

        assert (user_from_db.user_pubkey == user_pubkey)
        assert (user_from_db.user_privkey == user_privkey)
        assert (user_from_db.donor_pubkey == donor_pubkey)
Ejemplo n.º 40
0
def get_logged_in_user(request):
  """
  <Purpose>
    Determine the user logged in to the current session.
    This function should not be used through the xmlrpc frontend as there is
    no concept of the session there.
  <Arguments>
    request
      The HttpRequest object of the user's request through the frontend.
  <Exceptions>
    DoesNotExistError
      If there is no user logged in to the current session.
  <Side Effects>
    None
  <Returns>
    The GeniUser object of the logged in user.
  """
  # See http://docs.djangoproject.com/en/dev/topics/auth/#authentication-in-web-requests
  # for an explanation of request.user.is_authenticated().
  if request.user.is_authenticated():
    return maindb.get_user(request.user.username)
  else:
    raise DoesNotExistError
Ejemplo n.º 41
0
def get_logged_in_user(request):
  """
  <Purpose>
    Determine the user logged in to the current session.
    This function should not be used through the xmlrpc frontend as there is
    no concept of the session there.
  <Arguments>
    request
      The HttpRequest object of the user's request through the frontend.
  <Exceptions>
    DoesNotExistError
      If there is no user logged in to the current session.
  <Side Effects>
    None
  <Returns>
    The GeniUser object of the logged in user.
  """
  # See http://docs.djangoproject.com/en/dev/topics/auth/#authentication-in-web-requests
  # for an explanation of request.user.is_authenticated().
  if request.user.is_authenticated():
    return maindb.get_user(request.user.username)
  else:
    raise DoesNotExistError
def setup_general():
    """
  <Purpose>
    Prepare all the general stuff in order to run the tests.

  <Arguments>
    None

  <Exceptions>
    None

  <Side Efects>
    None

  <Return>
    None
  """

    testlib.setup_test_db()

    # Make sure all the variables are its default values
    mockutil.mockutil_cleanup_variables()

    # Create a user who has the donation key.
    user_object = maindb.create_user(mockutil.testusername, "password",
                                     "*****@*****.**", "affiliation",
                                     "10 11", "2 2 2", mockutil.donor_key_str)

    # Create a database entry for the node
    node_object = maindb.create_node(mockutil.nodeid_key_str, mockutil.node_ip,
                                     mockutil.node_port, "10.0test", True,
                                     mockutil.per_node_key_str,
                                     mockutil.extra_vessel_name)

    # Create a donation for user
    maindb.create_donation(node_object, user_object, "Making a donation")

    testuser = maindb.get_user(mockutil.testusername)

    # Retrieve the info about the donation we just made.
    all_donations = maindb.get_donations_by_user(
        testuser, include_inactive_and_broken=True)
    node = all_donations[0].node

    global vessels_dict
    vessels_dict = vessels_dict_basic.copy()
    # Create 9 different vessels, assuming that the original vessel got split into 9.
    for i in range(9):
        vessels_dict["vessel" + str(i)] = {}
        vessels_dict["vessel" + str(i)]["userkeys"] = []
        vessels_dict["vessel" + str(i)]["ownerkey"] = rsa_string_to_publickey(
            node.owner_pubkey)
        vessels_dict["vessel" + str(i)]["ownerinfo"] = ""
        vessels_dict["vessel" + str(i)]["status"] = ""
        vessels_dict["vessel" + str(i)]["advertise"] = True

        maindb.create_vessel(node, "vessel" + str(i))

    # Setup all the mock functions
    mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test",
                                            vessels_dict)
    mockutil.mock_lockserver_calls()
    mockutil.mock_backend_generate_key([mockutil.per_node_key_str])
    mockutil.mock_nodemanager_get_vesselresources()
    mockutil.mock_transitionlib_do_advertise_lookup([mockutil.node_address])
    mockutil.mock_backend_set_vessel_owner_key()
def run_movingto_canonical_to_onepercentmanyevents():
    """
  <Purpose>
    Test the process of transitioning a node from the
    movingto_canonical state to the onepercentmanyevents
    state.

  <Arguments>
    None

  <Side Effects>
    None

  <Exceptions>
    AssertionError raised if test fails.

  <Return>
    None
  """

    print "Starting movingto_canonical to onepercentmanyevents test....."
    transitionlist = []

    onepercentmanyevents_resource_fd = file(
        transition_onepercentmanyevents_to_canonical.
        RESOURCES_TEMPLATE_FILE_PATH)
    onepercentmanyevents_resourcetemplate = onepercentmanyevents_resource_fd.read(
    )
    onepercentmanyevents_resource_fd.close()

    transitionlist.append(
        ("movingto_canonical", "onepercentmanyevents",
         node_transition_lib.split_vessels, node_transition_lib.noop, True,
         onepercentmanyevents_resourcetemplate))

    (success_count,
     failure_count) = node_transition_lib.do_one_processnode_run(
         transitionlist, "startstatename", 1)[0]

    assert (success_count == 1)
    assert (failure_count == 0)

    assert_database_info_active()

    assert (mockutil.set_vessel_owner_key_call_count == 0)

    # The count for setting user key list is 10, once for the extra vessel
    # and 9 times for splitting the vessel.
    assert (mockutil.set_vessel_user_keylist_call_count == 10)

    # Retrieve the donated node and check its status with the database.
    testuser = maindb.get_user(mockutil.testusername)
    all_donations = maindb.get_donations_by_user(
        testuser, include_inactive_and_broken=True)
    node = all_donations[0].node

    vessel_list_per_node = maindb.get_vessels_on_node(node)

    # Testing to see if the vessels were created after split_vessels was called
    assert (mockutil.split_vessel_call_count == 9)
    assert (len(vessel_list_per_node) == 9)

    for i in range(len(vessel_list_per_node)):
        # Note that the vessel names go from 1-9 rather then 0-8
        assert (vessel_list_per_node[i].node == node)
        assert (vessel_list_per_node[i].name == "new_vessel" + str(1 + i))

    assert (node.extra_vessel_name == "extra_vessel_split9")
Ejemplo n.º 44
0
def register_user(username, password, email, affiliation, pubkey=None):
  """
  <Purpose>
    Creates a user record with the specified information and sets any additional
    information necessary for the user record to be complete.
  <Arguments>
    username
    password
    email
    affiliation
    pubkey
      Optional. A string. If not provided, a key pair will be generated for this user.
  <Exceptions>
    UsernameAlreadyExistsError
      If there is already a user with the specified username.
    ValidationError
      If any of the arguments contains invalid values or if the username is the
      same as the password.
  <Side Effects>
    The user record in the django db is created as well as a user record in the
    corresponding user profile table that stores our custom information. A port
    will be assigned to the user and the user's donation keys will be set.
  <Returns>
    GeniUser instance (our GeniUser model, not the django User) corresponding to the
    newly registered user.
  """
  # If the frontend code that called this function wants to know which field
  # is invalid, it must call the validation functions itself before making the
  # call to register_user().
  # These will raise a ValidationError if any of the fields are invalid.
  # These ensure that the data is of the correct type (e.g. a string) as well as
  # that we like the content of the variable.
  validations.validate_username(username)
  validations.validate_password(password)
  validations.validate_username_and_password_different(username, password)
  validations.validate_email(email)
  validations.validate_affiliation(affiliation)
  if pubkey is not None:
    validations.validate_pubkey_string(pubkey)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, username)
  try:
    # Ensure there is not already a user with this username.
    try:
      # Raises a DoesNotExistError if the user doesn't exist.
      maindb.get_user(username)
      raise UsernameAlreadyExistsError
    except DoesNotExistError:
      # This is what we wanted: the username isn't already taken.
      pass
    
    # Get a key pair from the keygen api if the user didn't supply their own pubkey.
    if pubkey is None:
      (pubkey, privkey) = keygen.generate_keypair()
    else:
      privkey = None
    
    # Generate a donor key for this user. This is done through the backend
    # as the private key must be stored in the keydb, which the website cannot
    # directly access.
    keydescription = "donor:" + username
    donor_pubkey = backend.generate_key(keydescription)
    
    # Create the user record.
    geniuser = maindb.create_user(username, password, email, affiliation, pubkey, privkey, donor_pubkey)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
    
  return geniuser
def setup_general():
  """
  <Purpose>
    Prepare all the general stuff in order to run the tests.

  <Arguments>
    None

  <Exceptions>
    None

  <Side Efects>
    None

  <Return>
    None
  """

  testlib.setup_test_db()

  # Make sure all the variables are its default values
  mockutil.mockutil_cleanup_variables()

  # Create a user who has the donation key.
  user_object = maindb.create_user(mockutil.testusername, "password", "*****@*****.**", "affiliation",
                    "10 11", "2 2 2", mockutil.donor_key_str)

  # Create a database entry for the node
  node_object = maindb.create_node(mockutil.nodeid_key_str, mockutil.node_ip, mockutil.node_port, "10.0test",
                                  True, mockutil.per_node_key_str, mockutil.extra_vessel_name)


  # Create a donation for user
  maindb.create_donation(node_object, user_object, "Making a donation")

  testuser = maindb.get_user(mockutil.testusername)

  # Retrieve the info about the donation we just made.
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  global vessels_dict
  vessels_dict = vessels_dict_basic.copy()
  # Create 9 different vessels, assuming that the original vessel got split into 9.
  for i in range(9):
    vessels_dict["vessel"+str(i)]={}
    vessels_dict["vessel"+str(i)]["userkeys"] = []
    vessels_dict["vessel"+str(i)]["ownerkey"] = rsa_string_to_publickey(node.owner_pubkey)
    vessels_dict["vessel"+str(i)]["ownerinfo"] = ""
    vessels_dict["vessel"+str(i)]["status"] = ""
    vessels_dict["vessel"+str(i)]["advertise"] = True

    maindb.create_vessel(node, "vessel"+str(i))


  # Setup all the mock functions
  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)
  mockutil.mock_lockserver_calls()
  mockutil.mock_backend_generate_key([mockutil.per_node_key_str])
  mockutil.mock_nodemanager_get_vesselresources()
  mockutil.mock_transitionlib_do_advertise_lookup([mockutil.node_address])
  mockutil.mock_backend_set_vessel_owner_key()
Ejemplo n.º 46
0
def register_user(username, password, email, affiliation, pubkey=None):
  """
  <Purpose>
    Creates a user record with the specified information and sets any additional
    information necessary for the user record to be complete.
  <Arguments>
    username
    password
    email
    affiliation
    pubkey
      Optional. A string. If not provided, a key pair will be generated for this user.
  <Exceptions>
    UsernameAlreadyExistsError
      If there is already a user with the specified username.
    ValidationError
      If any of the arguments contains invalid values or if the username is the
      same as the password.
  <Side Effects>
    The user record in the django db is created as well as a user record in the
    corresponding user profile table that stores our custom information. A port
    will be assigned to the user and the user's donation keys will be set.
  <Returns>
    GeniUser instance (our GeniUser model, not the django User) corresponding to the
    newly registered user.
  """
  # If the frontend code that called this function wants to know which field
  # is invalid, it must call the validation functions itself before making the
  # call to register_user().
  # These will raise a ValidationError if any of the fields are invalid.
  # These ensure that the data is of the correct type (e.g. a string) as well as
  # that we like the content of the variable.
  validations.validate_username(username)
  validations.validate_password(password)
  validations.validate_username_and_password_different(username, password)
  validations.validate_email(email)
  validations.validate_affiliation(affiliation)
  if pubkey is not None:
    validations.validate_pubkey_string(pubkey)
  
  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, username)
  try:
    # Ensure there is not already a user with this username.
    try:
      # Raises a DoesNotExistError if the user doesn't exist.
      maindb.get_user(username)
      raise UsernameAlreadyExistsError
    except DoesNotExistError:
      # This is what we wanted: the username isn't already taken.
      pass
    
    # Get a key pair from the keygen api if the user didn't supply their own pubkey.
    if pubkey is None:
      (pubkey, privkey) = keygen.generate_keypair()
    else:
      privkey = None
    
    # Generate a donor key for this user. This is done through the backend
    # as the private key must be stored in the keydb, which the website cannot
    # directly access.
    keydescription = "donor:" + username
    donor_pubkey = backend.generate_key(keydescription)
    
    # Create the user record.
    geniuser = maindb.create_user(username, password, email, affiliation, pubkey, privkey, donor_pubkey)
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
    
  return geniuser
Ejemplo n.º 47
0
def acquire_vessels(geniuser, vesselcount, vesseltype):
  """
  <Purpose>
    Acquire unused vessels of a given type for a user. For information on how
    the specified vesseltype affects which vessels will be considered
    to satisfy the request, see the type-specific functions that are called
    by this function.
  <Arguments>
    geniuser
      The GeniUser which will be assigned the vessels.
    vesselcount
      The number of vessels to acquire (a positive integer).
    vesseltype
      The type of vessels to acquire. One of either 'lan', 'wan', 'nat', or 'rand'.
  <Exceptions>
    UnableToAcquireResourcesError
      If not able to acquire the requested vessels (in this case, no vessels
      will be acquired).
    InsufficientUserResourcesError
      The user does not have enough vessel credits to acquire the number of
      vessels requested.
  <Side Effects>
    A total of 'vesselcount' previously-unassigned vessels of the specified
    vesseltype have been acquired by the user.
  <Returns>
    A list of the vessels as a result of this function call.
  """
  assert_geniuser(geniuser)
  assert_positive_int(vesselcount)
  assert_str(vesseltype)

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Ensure the user is allowed to acquire these resources. This call will
    # raise an InsufficientUserResourcesError if the additional vessels would
    # cause the user to be over their limit.
    maindb.require_user_can_acquire_resources(geniuser, vesselcount)
    
    if vesseltype == 'wan':
      acquired_list = vessels.acquire_wan_vessels(lockserver_handle, geniuser, vesselcount)
    elif vesseltype == 'lan':
      acquired_list = vessels.acquire_lan_vessels(lockserver_handle, geniuser, vesselcount)
    elif vesseltype == 'nat':
      acquired_list = vessels.acquire_nat_vessels(lockserver_handle, geniuser, vesselcount)
    elif vesseltype == 'rand':
      acquired_list = vessels.acquire_rand_vessels(lockserver_handle, geniuser, vesselcount)
    else:
      raise ProgrammerError("Vessel type '%s' is not a valid type" % vesseltype)
    
    return acquired_list
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
def run_movingto_canonical_to_onepercentmanyevents():
  """
  <Purpose>
    Test the process of transitioning a node from the
    movingto_canonical state to the onepercentmanyevents
    state.

  <Arguments>
    None

  <Side Effects>
    None

  <Exceptions>
    AssertionError raised if test fails.

  <Return>
    None
  """

  print "Starting movingto_canonical to onepercentmanyevents test....."
  transitionlist = []

  onepercentmanyevents_resource_fd = file(transition_onepercentmanyevents_to_canonical.RESOURCES_TEMPLATE_FILE_PATH)
  onepercentmanyevents_resourcetemplate = onepercentmanyevents_resource_fd.read()
  onepercentmanyevents_resource_fd.close()

  transitionlist.append(("movingto_canonical", "onepercentmanyevents",
                         node_transition_lib.split_vessels,
                         node_transition_lib.noop, True, 
                         onepercentmanyevents_resourcetemplate))



  (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

  assert(success_count == 1)
  assert(failure_count == 0)

  assert_database_info_active()

  assert(mockutil.set_vessel_owner_key_call_count == 0)

  # The count for setting user key list is 10, once for the extra vessel
  # and 9 times for splitting the vessel.
  assert(mockutil.set_vessel_user_keylist_call_count == 10)

  # Retrieve the donated node and check its status with the database.
  testuser = maindb.get_user(mockutil.testusername)
  all_donations = maindb.get_donations_by_user(testuser, include_inactive_and_broken=True)
  node = all_donations[0].node

  vessel_list_per_node = maindb.get_vessels_on_node(node)

  # Testing to see if the vessels were created after split_vessels was called
  assert(mockutil.split_vessel_call_count == 9)
  assert(len(vessel_list_per_node) == 9)

  for i in range(len(vessel_list_per_node)):
    # Note that the vessel names go from 1-9 rather then 0-8
    assert(vessel_list_per_node[i].node == node)
    assert(vessel_list_per_node[i].name == "new_vessel"+str(1+i))

  assert(node.extra_vessel_name == "extra_vessel_split9")
Ejemplo n.º 49
0
def acquire_vessels(geniuser, vesselcount, vesseltype):
  """
  <Purpose>
    Acquire unused vessels of a given type for a user. For information on how
    the specified vesseltype affects which vessels will be considered
    to satisfy the request, see the type-specific functions that are called
    by this function.
  <Arguments>
    geniuser
      The GeniUser which will be assigned the vessels.
    vesselcount
      The number of vessels to acquire (a positive integer).
    vesseltype
      The type of vessels to acquire. One of either 'lan', 'wan', 'nat', or 'rand'.
  <Exceptions>
    UnableToAcquireResourcesError
      If not able to acquire the requested vessels (in this case, no vessels
      will be acquired).
    InsufficientUserResourcesError
      The user does not have enough vessel credits to acquire the number of
      vessels requested.
  <Side Effects>
    A total of 'vesselcount' previously-unassigned vessels of the specified
    vesseltype have been acquired by the user.
  <Returns>
    A list of the vessels as a result of this function call.
  """
  assert_geniuser(geniuser)
  assert_positive_int(vesselcount)
  assert_str(vesseltype)

  # Lock the user.
  lockserver_handle = lockserver.create_lockserver_handle()
  lockserver.lock_user(lockserver_handle, geniuser.username)
  
  try:
    # Make sure the user still exists now that we hold the lock. Also makes
    # sure that we see any changes made to the user before we obtained the lock.
    try:
      geniuser = maindb.get_user(geniuser.username)
    except DoesNotExistError:
      raise InternalError(traceback.format_exc())
    
    # Ensure the user is allowed to acquire these resources. This call will
    # raise an InsufficientUserResourcesError if the additional vessels would
    # cause the user to be over their limit.
    maindb.require_user_can_acquire_resources(geniuser, vesselcount)
    
    if vesseltype == 'wan':
      acquired_list = vessels.acquire_wan_vessels(lockserver_handle, geniuser, vesselcount)
    elif vesseltype == 'lan':
      acquired_list = vessels.acquire_lan_vessels(lockserver_handle, geniuser, vesselcount)
    elif vesseltype == 'nat':
      acquired_list = vessels.acquire_nat_vessels(lockserver_handle, geniuser, vesselcount)
    elif vesseltype == 'rand':
      acquired_list = vessels.acquire_rand_vessels(lockserver_handle, geniuser, vesselcount)
    else:
      raise ProgrammerError("Vessel type '%s' is not a valid type" % vesseltype)
    
    return acquired_list
    
  finally:
    # Unlock the user.
    lockserver.unlock_user(lockserver_handle, geniuser.username)
    lockserver.destroy_lockserver_handle(lockserver_handle)
def run_multiple_donation_test():
  """
  <Purpose>
    The purpose of this test is to see how the transtion script would
    react if we provide a dictionary where a vessel is in the acceptdonation
    state but the node has already in the canonical state. This is possible
    if the node had two vessel in the acceptdonation state to start with.
    This is essentially if the node has two donations. Currently we don't handle
    multiple donations from the second node, so when we run the test, the success
    count should be 0 and the failure count should be 1. Also the name of the extra
    vessel should not change.

  <Arguments>
    None

  <Exceptions>
    None

  <Side Effects>
    None

  <Return>
    None
  """
 
  # Have the extra vessel in canonical form
  vessels_dict[mockutil.extra_vessel_name]["userkeys"] = [node_transition_lib.transition_state_keys['canonical']]

  # Have a second vessel in acceptdonation state. Essentially a second donation.
  vessels_dict["second_donation"] = {"userkeys" : [node_transition_lib.transition_state_keys['acceptdonation']],
                                   "ownerkey" : mockutil.donor_key,
                                   "ownerinfo" : "",
                                   "status" : "",
                                   "advertise" : True}

  # Create a database entry for the node
  node_object = maindb.create_node(mockutil.nodeid_key_str, mockutil.node_ip, mockutil.node_port, "10.0test",
                                  False, mockutil.per_node_key_str, mockutil.extra_vessel_name)
  user_object = maindb.get_user(mockutil.testusername)
  # Create a donation for user
  maindb.create_donation(node_object, user_object, "Making a donation")
  
  # Register the new vesseldict so get_info returns this new modified vesseldict
  mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test", vessels_dict)




  transitionlist = []

  transitionlist.append(("acceptdonation", "canonical", 
                         node_transition_lib.noop,
                         node_transition_lib.noop, False))

  print "Running test where database has record of node, no record of donation and node has donor key"

  (success_count, failure_count) = node_transition_lib.do_one_processnode_run(transitionlist, "startstatename", 1)[0]

  assert(success_count == 0)
  assert(failure_count == 1)

  assert_database_info()

  assert(mockutil.set_vessel_owner_key_call_count == 0)
  assert(mockutil.set_vessel_user_keylist_call_count == 0)
Ejemplo n.º 51
0
# Modules to make available for convenience so the names are available in the
# ipython shell. Just a lazy way to not have to execute these lines individually
# in a new shell.
from seattlegeni.website.control import interface
from seattlegeni.common.api import backend
from seattlegeni.common.api import keydb
from seattlegeni.common.api import keygen
from seattlegeni.common.api import lockserver
from seattlegeni.common.api import maindb
from seattlegeni.common.api import nodemanager

# grab a few objects to play with
g = maindb.get_user('user0')
(v, v2) = maindb.get_available_wan_vessels(g, 2)[:2]

def run_multiple_donation_test():
    """
  <Purpose>
    The purpose of this test is to see how the transtion script would
    react if we provide a dictionary where a vessel is in the acceptdonation
    state but the node has already in the canonical state. This is possible
    if the node had two vessel in the acceptdonation state to start with.
    This is essentially if the node has two donations. Currently we don't handle
    multiple donations from the second node, so when we run the test, the success
    count should be 0 and the failure count should be 1. Also the name of the extra
    vessel should not change.

  <Arguments>
    None

  <Exceptions>
    None

  <Side Effects>
    None

  <Return>
    None
  """

    # Have the extra vessel in canonical form
    vessels_dict[mockutil.extra_vessel_name]["userkeys"] = [
        node_transition_lib.canonicalpublickey
    ]

    # Have a second vessel in acceptdonation state. Essentially a second donation.
    vessels_dict["second_donation"] = {
        "userkeys": [node_transition_lib.acceptdonationpublickey],
        "ownerkey": mockutil.donor_key,
        "ownerinfo": "",
        "status": "",
        "advertise": True
    }

    # Create a database entry for the node
    node_object = maindb.create_node(mockutil.nodeid_key_str, mockutil.node_ip,
                                     mockutil.node_port, "10.0test", False,
                                     mockutil.per_node_key_str,
                                     mockutil.extra_vessel_name)
    user_object = maindb.get_user(mockutil.testusername)
    # Create a donation for user
    maindb.create_donation(node_object, user_object, "Making a donation")

    # Register the new vesseldict so get_info returns this new modified vesseldict
    mockutil.mock_nodemanager_get_node_info(mockutil.nodeid_key, "10.0test",
                                            vessels_dict)

    transitionlist = []

    transitionlist.append(
        (("donation_state", node_transition_lib.acceptdonationpublickey),
         ("canonical_state", node_transition_lib.canonicalpublickey),
         node_transition_lib.noop, node_transition_lib.noop))

    print "Running test where database has record of node, no record of donation and node has donor key"

    (success_count,
     failure_count) = node_transition_lib.do_one_processnode_run(
         transitionlist, "startstatename", 1)[0]

    assert (success_count == 0)
    assert (failure_count == 1)

    assert_database_info()

    assert (mockutil.set_vessel_owner_key_call_count == 0)
    assert (mockutil.set_vessel_user_keylist_call_count == 0)