Beispiel #1
0
    def login(self, username, password):
        """Sends request to Controller server and
        get the status on login request"""
        self.logger.info('CLIENT : entering login method')
        if not os.path.isdir(self.path):
            os.makedirs(self.path, 0o755)
        if os.path.isfile(self.token_file):
            os.remove(self.token_file)

        if not username:
            self.logger.error('CLIENT : Empty username passed. Exiting.')
            raise ControllerClientResponseException("Username can't be empty",
                                                    error_codes.empty_uid)
        if not password:
            self.logger.error('CLIENT : Empty password passed. Exiting.')
            raise ControllerClientResponseException("Password can't be empty",
                                                    error_codes.empty_uid)

        url = f"{self.server_path}/auth"
        credentials = {"uid": username, "pwd": password}
        self.logger.debug('CLIENT : Making post request to server')
        response = self.send_http_request(url=url,
                                          http_method=HTTPMethod.POST,
                                          data=credentials)

        self.save_token(token=response['access_token'])
        if 'relogin' in response and response['relogin']:
            self.logger.debug('CLIENT : already logged in. Saving new token.')
            return {"message": f"You are already logged in"}
        elif 'relogin' in response and not response['relogin']:
            self.logger.info(
                'CLIENT : Login successful. Writing token to file.')
            return {"message": f"Welcome, {username}!"}
        return response
Beispiel #2
0
    def sso_validate(self, validation_token):
        """
        Check whether SSO authentication is completed and successful
        Args:
            validation_token: sso validation token which is used to check if
                              a user has logged in or not.
        Returns:
        """
        # We keep requesting the sso server to test for
        interval_second = 2
        wait_second = 60
        start_time = time.time()
        while time.time() - start_time < wait_second:
            self.logger.debug('CLIENT : Making post request to server')
            url = f"{self.server_path}/sso/validate"
            data = {"validation_token": validation_token}
            try:

                response = self.send_http_request(url=url,
                                                  http_method=HTTPMethod.POST,
                                                  data=data)
                self.logger.info("Token validated")
                self.save_token(response["token"])
                return {"message": "SSO Login Successfull"}
            except ControllerClientResponseException:
                time.sleep(interval_second)
        self.logger.info('CLIENT : Existing SSO Login Method')
        raise ControllerClientResponseException("Session over without login",
                                                error_codes.server_error)
Beispiel #3
0
 def get_token(self):
     """Token is saved in the local file system for """
     token = None
     try:
         with open(self.token_file, "r") as f:
             token = f.read()
     except FileNotFoundError:
         self.logger.error("No Token Found. Need to Relogin")
         raise ControllerClientResponseException(
             "No Session found. Login again", error_codes.expired_token)
     return token
Beispiel #4
0
    def undeploy_project(self, argument):
        self.logger.info(f'CLIENT : Entering undeploy_project '
                         f'with arguments {argument}')
        if not argument:
            self.logger.error('CLIENT : No input arguments provided. Exiting.')
            raise ControllerClientResponseException(
                f"Please provide some input arguments ===",
                error_codes.incomplete_cluster_info)

        url = f'{self.server_path}/projects/deploy'
        response = self.send_http_request(url=url,
                                          http_method=HTTPMethod.DELETE,
                                          header={"token": self.get_token()},
                                          data=argument)
        self.logger.info('CLIENT : Project undeployed successfully.Exiting.')
        return {"message": "Project undeployed successfully!"}
Beispiel #5
0
    def deactivate_cluster(self, argument):

        self.logger.info('CLIENT : Entering deactivate_cluster method')
        if not argument:
            self.logger.error('CLIENT : No input arguments provided. Exiting.')
            raise ControllerClientResponseException(
                f"Please provide some input arguments ===",
                error_codes.incomplete_cluster_info)
        url = f'{self.server_path}/clusters'
        headers = {"token": self.get_token()}
        self.send_http_request(url=url,
                               http_method=HTTPMethod.DELETE,
                               header=headers,
                               data=argument)
        self.logger.info('CLIENT : Deactivation successful. Exiting.')
        return {"message": "Cluster deactivated."}
Beispiel #6
0
 def register_cluster(self, argument):
     self.logger.info('CLIENT : Entering register_cluster '
                      'with arguments {}'.format(argument))
     if not argument:
         self.logger.error('CLIENT : No input arguments provided. Exiting.')
         raise ControllerClientResponseException(
             f"Please provide some input arguments ===",
             error_codes.incomplete_cluster_info)
     url = f'{self.server_path}/clusters'
     headers = {"token": self.get_token()}
     response = self.send_http_request(url=url,
                                       http_method=HTTPMethod.POST,
                                       header=headers,
                                       data=argument)
     self.logger.info('CLIENT : Cluster registration successful.Exiting.')
     return {
         "message":
         f"Cluster successfully registered with "
         f"ID {response} ###"
     }
Beispiel #7
0
 def build_project(self, argument):
     self.logger.info(f'CLIENT : Entering build_project '
                      f'with arguments {argument}')
     if not argument:
         self.logger.error('CLIENT : No input arguments provided. Exiting.')
         raise ControllerClientResponseException(
             f"Please provide some input arguments ===",
             error_codes.incomplete_cluster_info)
     url = f'{self.server_path}/projects/build'
     response = self.send_http_request(url=url,
                                       http_method=HTTPMethod.POST,
                                       header={"token": self.get_token()},
                                       data=argument)
     self.logger.info('CLIENT : Project build successful.Exiting.')
     return {
         "message":
         "Project build successful!",
         "Build IDS":
         response,
         "Jenkins Pipeline":
         f"{self.config[self.JENKINS_SECTION][self.JENKINS_HOST]}"
         f"/blue/pipelines"
     }
Beispiel #8
0
 def send_http_request(self,
                       url: str,
                       http_method: HTTPMethod,
                       data=None,
                       header: dict = None):
     request = HTTPRequest(method=http_method,
                           url=url,
                           headers=header,
                           data=data)
     handler = HTTPHandler()
     try:
         response = handler.send_request(request)
         json_response = response.get_data_as_json()
         if not json_response:
             raise ControllerClientResponseException(
                 "Request Failed", error_codes.server_error)
         elif (json_response[self.API_JSON_OUTCOME] == self.API_JSON_SUCCESS
               and self.API_JSON_RESULTS in json_response):
             return json_response[self.API_JSON_RESULTS]
         elif (json_response[self.API_JSON_OUTCOME] == self.API_JSON_SUCCESS
               and self.API_JSON_RESULTS not in json_response):
             return {}
         elif (self.API_JSON_RESULTS in json_response
               and self.API_JSON_ERROR_CODE in json_response):
             raise ControllerClientResponseException(
                 json_response[self.API_JSON_RESULTS],
                 json_response[self.API_JSON_ERROR_CODE])
         elif self.API_JSON_ERROR_CODE in json_response:
             raise ControllerClientResponseException(
                 "Request Failed", json_response[self.API_JSON_ERROR_CODE])
         raise ControllerClientResponseException("Request Failed", -1)
     except (HTTPRequestFailedException, HTTPInvalidRequestException) as e:
         self.logger.error(str(e))
         raise ControllerClientResponseException("Server is not accessible",
                                                 error_codes.server_error)
     except JSONDecodeError as e:
         self.logger.error(str(e))
         raise ControllerClientResponseException(
             "Invalid response from server", error_codes.server_error)