Exemple #1
0
    def authorization_request() -> str:
        """
        Register your ESP in cloud. It takes password and login from aws_config.json
        :return: JSON Web Token
        """
        global cfg
        logging.debug("Authorization request function")
        headers = DEFAULT_JSON_HEADER
        url = cfg.api_url + API_AUTHORIZATION_URL
        body = {}
        body['is_removed'] = True
        body['created_at'] = 0
        body['username'] = cfg.api_login
        body['password'] = cfg.api_password

        logging.debug('LOGIN: {}, password: {}'.format(cfg.api_login, cfg.api_password))

        body = ujson.dumps(body)
        try:
            response = urequests.post(url, data=body, headers=headers)
        except IndexError as e:
            logging.info("No internet connection: {}".format(e))
            return ""
        except Exception as e:
            logging.info("Failed to authorize in API {}".format(e))
            return ""

        if response.status_code != '200' and response.status_code != 200:
            logging.error(response.text)
            return ""

        response_dict = response.json()
        jwt_token = response_dict.get("data")
        return jwt_token
Exemple #2
0
def exec(cmd, cwd=None, verbose=False):
    tag = '[%s]' % os.environ['PROJECT_NAME']
    if verbose:
        info('%s %s' % (tag, cmd))

    if isinstance(cmd, str):
        cmd = cmd.split()

    retry = 0
    max_retries = 3

    while (retry < max_retries):
        try:
            status = subprocess.run(cmd, capture_output=True, cwd=cwd, check=True)
            stdout = status.stdout.decode('utf-8').strip()
            stderr = status.stderr.decode('utf-8').strip()

            if verbose:
                if stdout:
                    print(stdout)
                if stderr:
                    print(stderr)

            return status
        except subprocess.CalledProcessError:
            retry += 1

            warning("last command failed. retries remaining: %s" % (max_retries - retry))
            sleep_time = 30 * retry
            warning('sleeping for %s seconds' % sleep_time)
            sleep(sleep_time)

            if retry == max_retries:
                pass
Exemple #3
0
    def get(self):

        cmd = self.request.path[1:]
        logger.info('path: %s', self.request.path)

        if self.request.path in ('/', 'index.html'):
            self.add_header('Content-Type', 'text/html')
            with open('./assets/index.html') as f:
                return self.write(f.read())

        fn = {
            'forward': self.move,
            'forward_stop': self.moveStop,
            'back': lambda: self.move(False),
            'back_stop': self.moveStop,
            'right': self.turn,
            'right_stop': self.turnStop,
            'left': lambda: self.turn(False),
            'left_stop': self.turnStop,
        }.get(cmd.lower(), lambda: self.car.stop())

        if not fn:
            res = 'unknown command: %s' % cmd
        else:
            directionX, directionY = self.car.direction

            fn()

            newDirectionX, newDirectionY = self.car.direction
            res = '%s: %s -> %s<br\>%s: %s -> %s' % ('Move', directionY,
                                                     newDirectionY, 'Turn',
                                                     directionX, newDirectionX)

        self.add_header('Content-Type', 'text/html')
        return self.write(str(res))
Exemple #4
0
    def save_certificates(config_dict: dict) -> None:
        """
        Save AWS certificates to files.
        :param config_dict: dict with credentials.
        :return: None
        """
        global cfg
        logging.debug("save_certificates()")
        try:
            mkdir(CERTIFICATES_DIR)
        except:
            pass

        if 'cert_pem' in config_dict.keys():
            certificate_string = config_dict['cert_pem']
            cfg.cert_pem = config_dict['cert_pem']
            with open(CERTIFICATE_PATH, "w", encoding="utf8") as infile:
                infile.write(certificate_string)

        if 'priv_key' in config_dict.keys():
            private_key_string = config_dict['priv_key']
            cfg.private_key = config_dict['priv_key']
            logging.info(private_key_string)
            with open(KEY_PATH, "w", encoding="utf8") as infile:
                infile.write(private_key_string)

        if 'cert_ca' in config_dict.keys():
            ca_certificate_string = config_dict['cert_ca']
            cfg.cert_ca = config_dict['cert_ca']
            with open(CA_CERTIFICATE_PATH, "w", encoding="utf8") as infile:
                infile.write(ca_certificate_string)
Exemple #5
0
    def save() -> None:
        """
        Save config to file.
        :return: None.
        """
        logging.debug("ESPConfig.save()")
        global cfg
        config_dict = cfg.as_dictionary

        with open(CONFIG_FILE_PATH, "w", encoding="utf8") as infile:
            dump(config_dict, infile)
        logging.info("New config saved!")
        def wrapper(*args, **kwargs):
            missing_params = [param for param in params if param not in request.args]
            if len(missing_params) > 0:
                message = 'Missing params: {}'.format(', '.join(missing_params))
                # Only respond with an error if this isn't an App Engine task. Tasks will attempt to retry in the event
                # they fail, but this failure is not recoverable, so respond successfully after logging.
                if 'X-AppEngine-TaskName' not in request.headers:
                    logging.info(message)
                    return error_response(400, message)
                else:
                    logging.error(message)
                    return '', 200

            return fn(*args, **kwargs)
Exemple #7
0
    def backup_repos(self, repos):
        info('[%s] backing up repositories' % self.type)

        for repo in repos:
            try:
                repo_name = get_repo_name(repo, self.type)
                path = os.path.join(self.directory, repo_name)

                git = Git(repo, path, repo_name, self.verbose)

                if os.path.isdir(path):
                    remote_refs = len(git.list_remote_refs())
                    if remote_refs == 0:
                        continue

                    git.fetch()
                    git.reset_origin_hard()
                else:
                    git.clone()
            except Exception:
                self.errors.append(repo_name)
Exemple #8
0
    def list_repositories(self):
        repos = []

        url = '%s/repositories/%s' % (self.api_url, self.organization)
        info('[bitbucket] listing repositories')

        get_next_page = True
        while get_next_page:
            http = Http(self.user, self.password)
            data = json.loads(http.get(url))

            for repo in data['values']:
                for link in repo['links']['clone']:
                    if link['name'] == 'ssh':
                        repos.append(link['href'])

            if 'next' in data:
                url = data['next']
            else:
                get_next_page = False

        return sorted(repos)
Exemple #9
0
 def stop(self):
     self.direction = None
     logger.info('car stopping: moving=%s, turning=%s', self.moving,
                 self.turning)
Exemple #10
0
            fn()

            newDirectionX, newDirectionY = self.car.direction
            res = '%s: %s -> %s<br\>%s: %s -> %s' % ('Move', directionY,
                                                     newDirectionY, 'Turn',
                                                     directionX, newDirectionX)

        self.add_header('Content-Type', 'text/html')
        return self.write(str(res))


def make_app():
    return tornado.web.Application([
        (r"/.*", MainHandler),
    ])


if __name__ == "__main__":
    Signal.default().setup()
    try:
        app = make_app()
        port = 80 if inPi else 8080
        app.listen(port)
        logger.info('started server on %s...', port)
        tornado.ioloop.IOLoop.current().start()

    except Exception as ex:
        logger.error('server error: %s', ex)
    finally:
        Signal.default().cleanup()