def initialise_session(session):
    """
    Initialises a session with the uts server. (Not 100% sure if this is required).
    """
    first_url = BASE_URL + 'student'

    response = session.get(first_url)
    if response.status_code != 200:
        request_failed(failed_response=response,
                       message='Unable to initialise session')

    return session
Beispiel #2
0
def create_vm(**_):
    random_suffix_value = utils.random_suffix_generator()
    vm_name = ctx.node.properties[constants.VM_PREFIX]+random_suffix_value
    ctx.logger.info("Creating new virtual machine: {0}".format(vm_name))
    storage_account_name = ctx.instance.runtime_properties[constants.STORAGE_ACCOUNT_KEY]

    headers, location, subscription_id = auth.get_credentials()
    resource_group_name = ctx.instance.runtime_properties[constants.RESOURCE_GROUP_KEY]

    try:
        virtual_machine_params = get_virtual_machine_params(location, random_suffix_value, resource_group_name,
                                                            storage_account_name, subscription_id, vm_name)
        virtual_machine_url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Compute/virtualMachines/'+vm_name+'?validating=true&api-version='+constants.api_version
        response_vm = requests.put(url=virtual_machine_url, data=virtual_machine_params, headers=headers)
        if response_vm.text:
            ctx.logger.info("create_vm:{0} response_vm.text is {1}".format(vm_name, response_vm.text))
            if utils.request_failed("{0}:{1}".format('create_vm', vm_name), response_vm):
                raise NonRecoverableError("Virtual Machine {0} could not be created".format(vm_name))
        elif response_vm:
            ctx.logger.info("create_vm:{0} response_vm is {1}".format(vm_name, response_vm))
        else:
            ctx.logger.info("create_vm:{0} response_vm is empty".format(vm_name))
        ctx.instance.runtime_properties[constants.VM_KEY] = vm_name
    except:
        ctx.logger.info("Virtual Machine {0} could not be created".format(vm_name))
        raise NonRecoverableError("Virtual Machine {0} could not be created".format(vm_name))
def login(session, student_number, password):
    """
    Logs the user in and returns a login token which is used as a GET parameter for further requests.
    """
    initialise_session(session)

    data = {'username': student_number, 'password': password}

    login_url = BASE_URL + 'rest/student/login'

    response = session.post(login_url, data=data)
    if response.status_code == 200:
        print('Login successful')
        return response.json()['token']
    else:
        request_failed(failed_response=response, message='Login failed.')
def create_resource_group(**_):
    resource_group_name = utils.set_resource_name(_get_resource_group_name, 'Resource group',
                                                  constants.RESOURCE_GROUP_KEY, constants.EXISTING_RESOURCE_GROUP_KEY,
                                                  constants.RESOURCE_GROUP_PREFIX)
    if resource_group_name is None:
        # Using an existing resource group, so don't create anything
        return

    headers, location, subscription_id = auth.get_credentials()

    resource_group_url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'?api-version='+constants.api_version_resource_group

    try:
        ctx.logger.info("Creating a new Resource group: {}".format(resource_group_name))
        resource_group_params = json.dumps({"name": resource_group_name, "location": location})
        response_rg = requests.put(url=resource_group_url, data=resource_group_params, headers=headers)
        if response_rg.text:
            ctx.logger.info("create_resource_group {0} response_rg.text is {1}".format(resource_group_name, response_rg.text))
            if utils.request_failed("{0}:{1}".format('create_resource_group', resource_group_name), response_rg):
                raise NonRecoverableError("Resource group {0} could not be created".format(resource_group_name))

        ctx.instance.runtime_properties[constants.RESOURCE_GROUP_KEY] = resource_group_name
    except:
        ctx.logger.info("Resource Group {0} could not be created".format(resource_group_name))
        raise NonRecoverableError("Resource Group {0} could not be created".format(resource_group_name))
def register_subject(session, login_token, student_code, class_key):
    """
    Registers the user for a specific class.
    :param session: authenticated request.Session object
    :param login_token: login token
    :param student_code: student number
    :param class_key: class details in the form "{subject code}|{class type}|{activity code}" e.g.
    "31927_SPR_U_1_S|Cmp1|02"
    :return:
    """
    enrol_subject_url = BASE_URL + 'rest/student/changeActivity/'
    params = {'ss': login_token}

    class_key_split = class_key.split('|')

    subject_code = class_key_split[0]
    class_type = class_key_split[1]
    class_id = class_key_split[2]

    data = {
        'token': 'a',  # I have no idea why this needs to be sent.
        'student_code': student_code,
        'subject_code': subject_code,
        'activity_group_code': class_type,
        'activity_code': class_id
    }

    response = session.post(enrol_subject_url, params=params, data=data)
    if response.status_code == 200:
        print('Updated the subject. Successfully registered for: %s.' %
              class_key)
        print('Sending email notification now.')
        send_mail(subject='Updated the subject!',
                  message_body='Updated the subject!')
        sys.exit(0)
    else:
        request_failed(response, message='Unable to register for subject.')
Beispiel #6
0
def _start_vm_call(headers, vm_name, subscription_id, resource_group_name):
    ctx.logger.info("In _vm_is_started checking {}".format(vm_name))
    start_vm_url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Compute/virtualMachines/'+vm_name+'/start?api-version='+constants.api_version
    response_start_vm = requests.post(start_vm_url, headers=headers)
    if response_start_vm.text:
        ctx.logger.info("_start_vm_call {} response_start_vm.text is {}".format(vm_name, response_start_vm.text))
        ctx.logger.info("_start_vm_call:{} status code is {}".format(vm_name, response_start_vm.status_code))
        if utils.request_failed("{}:{}".format('_start_vm_call', vm_name), response_start_vm):
            raise NonRecoverableError("Virtual Machine {} could not be started".format(vm_name))
    if response_start_vm.status_code:
        ctx.logger.info("_start_vm_call:{} - Status code is {}".format(vm_name, response_start_vm.status_code))
        if response_start_vm.status_code == 202:
            ctx.instance.runtime_properties[constants.REQUEST_ACCEPTED] = True
            return True
        elif response_start_vm.status_code == 200:
            ctx.instance.runtime_properties[constants.REQUEST_ACCEPTED] = True
            return True
        else:
            return False
    raise NonRecoverableError("_start_vm_call:{} - No Status code for vm {}".format(vm_name, response_start_vm.status_code))
def create_security_group(**_):
    if constants.USE_EXTERNAL_RESOURCE in ctx.node.properties and ctx.node.properties[constants.USE_EXTERNAL_RESOURCE]:
        if constants.EXISTING_SECURITY_GROUP_KEY in ctx.node.properties:
            existing_security_group_name = ctx.node.properties[constants.EXISTING_SECURITY_GROUP_KEY]
            if existing_security_group_name:
                security_group_exists = _get_security_group_name(existing_security_group_name)
                if not security_group_exists:
                    raise NonRecoverableError("Security group {} doesn't exist your Azure account".format(existing_security_group_name))
            else:
                raise NonRecoverableError("The value of '{}' in the input, is empty".format(constants.EXISTING_SECURITY_GROUP_KEY))
        else:
            raise NonRecoverableError("'{}' was specified, but '{}' doesn't exist in the input".format('use_external_resource',constants.EXISTING_SECURITY_GROUP_KEY))

        ctx.instance.runtime_properties[constants.SECURITY_GROUP_KEY] = ctx.node.properties[constants.EXISTING_SECURITY_GROUP_KEY]
        return
    
    headers, location, subscription_id = auth.get_credentials()
    resource_group_name = ctx.instance.runtime_properties[constants.RESOURCE_GROUP_KEY]

    if constants.SECURITY_GROUP_KEY in ctx.instance.runtime_properties:
        security_group_name = ctx.instance.runtime_properties[constants.SECURITY_GROUP_KEY]
    else:
        random_suffix_value = utils.random_suffix_generator()
        security_group_name = constants.SECURITY_GROUP_PREFIX+random_suffix_value

    security_group_url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/microsoft.network/networkSecurityGroups/'+security_group_name+'?api-version='+constants.api_version
    try:
        ctx.logger.info("Creating a new security group: {0}".format(security_group_name))
        security_group_params = json.dumps({
        "location": location,
        "tags": {
            "key": "value"
        },
        "properties": {
            "securityRules": [
                {
                    "name": constants.nsg_rule_name,
                    "properties": {
                        "description": constants.NSG_RULES_DESCRIPTION,
                        "protocol": ctx.node.properties['security_group_protocol'],
                        "sourcePortRange": ctx.node.properties['security_group_sourcePortRange'] ,
                        "destinationPortRange": ctx.node.properties['security_group_destinationPortRange'],
                        "sourceAddressPrefix": ctx.node.properties['security_group_sourceAddressPrefix'],
                        "destinationAddressPrefix": ctx.node.properties['security_group_destinationAddressPrefix'],
                        "access": ctx.node.properties['security_group_access'],
                        "priority": ctx.node.properties['security_group_priority'],
                        "direction": ctx.node.properties['security_group_direction']
                    }
                }
             ]
          }
        })
        response_nsg = requests.put(url=security_group_url, data=security_group_params, headers=headers)
        if response_nsg.text:
            ctx.logger.info("create_security_group {0} response_nsg.text is {1}".format(security_group_name, response_nsg.text))
            if utils.request_failed("{0}:{1}".format('create_security_group', security_group_name), response_nsg):
                raise NonRecoverableError("create_security_group {0} could not be created".format(security_group_name))
        ctx.instance.runtime_properties[constants.SECURITY_GROUP_KEY] = security_group_name
    except:
        ctx.logger.info("Security Group {0} could not be created".format(security_group_name))
        raise NonRecoverableError("Security Group {} could not be created".format(security_group_name))