Example #1
0
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.channel = None
        self.event_recu = Event()
class TransmettreCertificatTransactionTest:
    def __init__(self):
        self.contexte = ContexteRessourcesMilleGrilles()
        self.contexte.initialiser(init_message=True)

        self._logger = logging.getLogger('test')
        self.generateur_transaction = GenerateurTransaction(
            self.contexte.configuration, self.contexte.message_dao)

        self.enveloppe_certificat = None

    def charger_certificat(self, fichier):

        verificateur = VerificateurCertificats(self.contexte)
        self.enveloppe_certificat = verificateur.charger_certificat(fichier)
        verificateur.verifier_chaine(self.enveloppe_certificat)

    def transmettre(self):
        certificat = self.enveloppe_certificat.certificat
        self._logger.debug("Certificat a transmettre: %s" % str(certificat))
        certificat_pem = str(
            certificat.public_bytes(serialization.Encoding.PEM), 'utf-8')
        self._logger.debug("Certificat string: %s" % certificat_pem)

        message = {
            'certificat_pem': certificat_pem,
            'fingerprint': self.enveloppe_certificat.fingerprint_ascii
        }

        domaine = '%s.%s' % (ConstantesPki.DOMAINE_NOM,
                             ConstantesPki.TRANSACTION_EVENEMENT_CERTIFICAT)
        self.generateur_transaction.soumettre_transaction(message, domaine)
class NotificationActionExempleTest:

    def __init__(self):
        self.configuration = TransactionConfiguration()
        self.configuration.loadEnvironment()

        self.message_dao = PikaDAO(self.configuration)
        self.message_dao.connecter()

        self.generateur_transaction = GenerateurTransaction(self.configuration, self.message_dao)

    def deconnecter(self):
        self.message_dao.deconnecter()

    def test1(self):

        # temps_lecture_ajuste = temps_lecture + datetime.timedelta(hours=4)
        domaine = TachesConstantes.TRANSACTION_ACTION_TACHE

        transaction_message = dict({
            TachesConstantes.LIBELLE_ID_NOTIFICATION: '5c152457e094095d8c8d314e',
            TachesConstantes.LIBELLE_ACTION: TachesConstantes.ACTION_VUE,
            TachesConstantes.LIBELLE_DATE_ATTENTE_ACTION: 180
        })

        self.generateur_transaction.soumettre_transaction(transaction_message, domaine)

        print("Sent notification domaine %s: %s" % (domaine, transaction_message))
    def __init__(self):
        self.configuration = TransactionConfiguration()
        self.configuration.loadEnvironment()

        self.message_dao = PikaDAO(self.configuration)
        self.message_dao.connecter()

        self.generateur_transaction = GenerateurTransaction(self.configuration, self.message_dao)
Example #5
0
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.uuid_blogpost = '3c38abee-3d68-11ea-be1a-00155d011f09'

        self.channel = None
        self.event_recu = Event()
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.fichier_fuuid = "39c1e1b0-b6ee-11e9-b0cd-d30e8fab842j"

        self.channel = None
        self.event_recu = Event()
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.channel = None
        self.event_recu = Event()

        self.noeud_id = '6bee12f0-9284-42dc-83a2-52d50c69de4a'
    def __init__(self):
        self.contexte = ContexteRessourcesMilleGrilles()
        self.contexte.initialiser(init_message=True)

        self._logger = logging.getLogger('test')
        self.generateur_transaction = GenerateurTransaction(
            self.contexte.configuration, self.contexte.message_dao)

        self.enveloppe_certificat = None
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.collection_uuid = "1383dca0-37dc-11ea-acfe-00155d011f09"
        self.collection_figee = "4df31516-3aea-11ea-be1a-00155d011f09"

        self.channel = None
        self.event_recu = Event()
    def __init__(self):
        super().__init__(contexte)
        self.__logger = logging.getLogger(__name__ + '.' + self.__class__.__name__)
        self.__logger.setLevel(logging.DEBUG)

        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.handler_backup_senseurspassifs = HandlerBackupDomaine(
            self.contexte,
            SenseursPassifsConstantes.DOMAINE_NOM,
            SenseursPassifsConstantes.COLLECTION_TRANSACTIONS_NOM,
            SenseursPassifsConstantes.COLLECTION_DOCUMENTS_NOM)
        self.handler_grosfichiers = HandlerBackupGrosFichiers(self.contexte)

        self.channel = None
        self.event_recu = Event()

        # Preparer URL de connexion a consignationfichiers
        self.url_consignationfichiers = 'https://%s:%s' % (
            self._contexte.configuration.serveur_consignationfichiers_host,
            self._contexte.configuration.serveur_consignationfichiers_port,
        )

        self.idmg = 'CRnbtUbwzUuTg2h88ALe4Phg441Emgp8FibqkJ'
Example #11
0
    def __init__(self, connecter=True):
        contexte = ContexteRessourcesMilleGrilles()
        contexte.initialiser(connecter=connecter)

        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)
        self.channel = None
        self.event_recu = Event()
        self.messages = list()
Example #12
0
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.queue_name = None

        self.channel = None
        self.event_recu = Event()
        self.collection_transactions = self.contexte.document_dao.get_collection(SenseursPassifsConstantes.COLLECTION_TRANSACTIONS_NOM)
        self.collection_documents = self.contexte.document_dao.get_collection(
            SenseursPassifsConstantes.COLLECTION_DOCUMENTS_NOM)

        self.temps_debut_rapport = datetime.datetime(year=2020, month=1, day=1)
        self.temps_fin_rapport = datetime.datetime(year=2020, month=2, day=1)

        self.filtre = {
            'en-tete.domaine': SenseursPassifsConstantes.TRANSACTION_DOMAINE_LECTURE,
            # 'uuid_senseur': {'$in': ['731bf65cf35811e9b135b827eb9064af']},
            SenseursPassifsConstantes.TRANSACTION_DATE_LECTURE: {
                '$gte': self.temps_debut_rapport.timestamp(),
                '$lt': self.temps_fin_rapport.timestamp(),
            },
        }

        self.regroupement_periode = {
            'year': {'$year': '$_evenements._estampille'},
            'month': {'$month': '$_evenements._estampille'},
            'day': {'$dayOfMonth': '$_evenements._estampille'},
            'hour': {'$hour': '$_evenements._estampille'},
        }

        self._regroupement_elem_numeriques = [
            # 'temperature', 'humidite', 'pression', 'millivolt', 'reserve'
            'temperature', 'humidite',
        ]

        # self._accumulateurs = ['max', 'min', 'avg']
        self._accumulateurs = ['avg']

        self.hint = {'_evenements._estampille': -1}
class MessagesSample(BaseCallback):

    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True, exclusive=True, callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck, queue=self.queue_name, no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(json.dumps(json.loads(body.decode('utf-8')), indent=4))
        print("Channel : " + str(ch))
        print("Method : " + str(method))
        print("Properties : " + str(properties))
        print("Channel virtual host : " + str(ch.connection.params.virtual_host))

    def commande_transmettre_catalogues(self):
        commande = {}
        domaineAction = 'commande.servicemonitor.' + Constantes.ConstantesServiceMonitor.COMMANDE_TRANSMETTRE_CATALOGUES

        enveloppe = self.generateur.transmettre_commande(
            commande,
            domaineAction,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.SECURITE_PROTEGE
        )

        print("Envoi : %s" % enveloppe)
        return enveloppe

    def executer(self):
        self.commande_transmettre_catalogues()
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)
        self.channel = None
        self.event_recu = Event()
        # self.thread_ioloop = Thread(target=self.run_ioloop)

        self.queue_name = None

        self.certificat_maitredescles = None
        self.cert_maitredescles_recu = Event()

        self.mot_de_passe = 'sjdpo-1824-JWAZ'

        # Charger cert MaitreDesCles pour pouvoir crypter contenu a transmettre
        with open('/home/mathieu/mgdev/certs/pki.maitrecles.cert',
                  'rb') as certificat_pem:
            certificat_courant_pem = certificat_pem.read()
            cert = x509.load_pem_x509_certificate(certificat_courant_pem,
                                                  backend=default_backend())
            self.certificat_courant = cert
            self.certificat_courant_pem = certificat_courant_pem.decode('utf8')
Example #15
0
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)
        self.channel = None
        self.event_recu = Event()
        # self.thread_ioloop = Thread(target=self.run_ioloop)

        self.certificat_maitredescles = None
        self.cert_maitredescles_recu = Event()

        self.mot_de_passe = 'sjdpo-1824-JWAZ'

        # Charger cert MaitreDesCles pour pouvoir crypter contenu a transmettre
        with open('/home/mathieu/mgdev/certs/pki.maitrecles.cert', 'rb') as certificat_pem:
            self.certificat_courant_pem = certificat_pem.read()
            self.clecert = EnveloppeCleCert()
            self.clecert.set_chaine_str(self.certificat_courant_pem.decode('utf-8'))
            self.clecert.cert_from_pem_bytes(self.certificat_courant_pem)
            # cert = x509.load_pem_x509_certificate(
            #     certificat_courant_pem,
            #     backend=default_backend()
            # )
            self.certificat_courant = self.clecert.cert
            self.certificat_courant_pem = self.certificat_courant_pem.decode('utf8')

        with open('/home/mathieu/mgdev/certs/pki.millegrille.cert', 'rb') as certificat_pem:
            self.certificat_millegrille_pem = certificat_pem.read()
            self.clecert_millegrille = EnveloppeCleCert()
            self.clecert_millegrille.set_chaine_str(self.certificat_millegrille_pem.decode('utf-8'))
            self.clecert_millegrille.cert_from_pem_bytes(self.certificat_millegrille_pem)
            # cert = x509.load_pem_x509_certificate(
            #     certificat_courant_pem,
            #     backend=default_backend()
            # )
            self.cert_millegrille = self.clecert_millegrille.cert
            self.cert_millegrille_pem = self.certificat_millegrille_pem.decode('utf8')
class TestEnvoyerRequete:

    def __init__(self, contexte):
        self.callback = TestCallback(contexte, self)
        self.generateur = GenerateurTransaction(contexte)

        self.reponse = None

    def envoyer_message_test_alerte(self):

        requete = {
            'requetes': [
                {
                    'type': 'mongodb',
                    "filtre": {
                        "_mg-libelle": "noeud.individuel",
                        "noeud": {
                            "$in": ["test"]
                        }
                    },
                    "projection": {
                        "noeud": 1,
                        "dict_senseurs": 1
                    }
                }
            ],
            # 'retour': {
            #     "routage": "reponse.%s" % message_dao.queue_reponse
            # }
        }

        # enveloppe_val = generateur.soumettre_transaction(requete, 'millegrilles.domaines.Principale.creerAlerte')
        enveloppe_requete = self.generateur.preparer_enveloppe(requete, 'millegrilles.domaines.SenseursPassifs.requete')
        self.generateur.transmettre_requete(enveloppe_requete, 'requete.millegrilles.domaines.SenseursPassifs.mongodb', Constantes.DEFAUT_MQ_EXCHANGE_NOEUDS)

        return enveloppe_requete
    def __init__(self, contexte):
        self.callback = TestCallback(contexte, self)
        self.generateur = GenerateurTransaction(contexte)

        self.reponse = None
Example #18
0
class MessagesSample(BaseCallback):

    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)
        self.channel = None
        self.event_recu = Event()
        # self.thread_ioloop = Thread(target=self.run_ioloop)

        self.certificat_maitredescles = None
        self.cert_maitredescles_recu = Event()

        self.mot_de_passe = 'sjdpo-1824-JWAZ'

        # Charger cert MaitreDesCles pour pouvoir crypter contenu a transmettre
        with open('/home/mathieu/mgdev/certs/pki.maitrecles.cert', 'rb') as certificat_pem:
            self.certificat_courant_pem = certificat_pem.read()
            self.clecert = EnveloppeCleCert()
            self.clecert.set_chaine_str(self.certificat_courant_pem.decode('utf-8'))
            self.clecert.cert_from_pem_bytes(self.certificat_courant_pem)
            # cert = x509.load_pem_x509_certificate(
            #     certificat_courant_pem,
            #     backend=default_backend()
            # )
            self.certificat_courant = self.clecert.cert
            self.certificat_courant_pem = self.certificat_courant_pem.decode('utf8')

        with open('/home/mathieu/mgdev/certs/pki.millegrille.cert', 'rb') as certificat_pem:
            self.certificat_millegrille_pem = certificat_pem.read()
            self.clecert_millegrille = EnveloppeCleCert()
            self.clecert_millegrille.set_chaine_str(self.certificat_millegrille_pem.decode('utf-8'))
            self.clecert_millegrille.cert_from_pem_bytes(self.certificat_millegrille_pem)
            # cert = x509.load_pem_x509_certificate(
            #     certificat_courant_pem,
            #     backend=default_backend()
            # )
            self.cert_millegrille = self.clecert_millegrille.cert
            self.cert_millegrille_pem = self.certificat_millegrille_pem.decode('utf8')

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True, exclusive=True, callback=self.queue_open)

    def queue_open(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck, queue=self.queue_name, no_ack=False)
        # self.event_recu.set()
        self.requete_cert_maitredescles()
        thread_executer = Thread(name="exec", target=self.executer)
        thread_executer.start()

    # def run_ioloop(self):
    #     self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(body)

        message_dict = json.loads(body)
        certificat_pem = message_dict.get('certificat')
        if certificat_pem is not None:
            cert = EnveloppeCleCert()
            try:
                cert.cert_from_pem_bytes(certificat_pem[0].encode('utf-8'))
                self.certificat_maitredescles = cert
                print("Recu certificat %s" % cert.fingerprint_b64)
            except:
                print("Erreur traitement certificat_pem")
            self.cert_maitredescles_recu.set()
        else:
            self.event_recu.set()
            if message_dict.get('certificats_pem'):
                for cert in message_dict.get('certificats_pem'):
                    print(cert)

        print(json.dumps(message_dict, indent=4))

    def requete_cert_maitredescles(self):
        requete_cert_maitredescles = {
            # Constantes.TRANSACTION_MESSAGE_LIBELLE_EVENEMENT: ConstantesMaitreDesCles.REQUETE_CERT_MAITREDESCLES
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_CERT_MAITREDESCLES,
            'abcd-1234',
            self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_trousseau_hebergement(self):
        requete = {
            'idmg': ['2aMvfBTqyfeQsMgSsYbtJuMeqUJ5TZV2iNiy2ES']
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete,
            'millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_TROUSSEAU_HEBERGEMENT,
            'abcd-1234',
            self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_decryptage_cle_fuuid(self):
        requete_cert_maitredescles = {
            'fuuid': "ddb0d8f0-f7b4-11ea-89ec-13126005a8b0"
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_DECRYPTAGE_GROSFICHIER,
            'abcd-1234',
            self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_cle_document(self):
        fingerprint = self.clecert.fingerprint

        requete_cert_maitredescles = {
            'fingerprint': fingerprint,
            'certificat': self.certificat_courant_pem,
            'domaine': 'MaitreDesComptes',
            'identificateurs_document': {
                "libelle": "proprietaire",
                "champ": "totp"
            }
        }

        print(requete_cert_maitredescles)

        self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_DECRYPTAGE_DOCUMENT,
            'abcd-1234',
            self.queue_name
        )

    def requete_decryptage_cle_fuuid_avecfingerprint(self):
        requete_cert_maitredescles = {
            'fuuid': "b4ecca10-1c2b-11ea-904a-7b4d1a2d4432",
            'fingerprint': '74fd5742aec60dd37f99c75df423008a10149018'
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_DECRYPTAGE_GROSFICHIER,
            'abcd-1234',
            self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_cle_racine(self):
        # Attendre le certificat de maitre des cles pour chiffrer la cle
        self.cert_maitredescles_recu.wait(5)

        mot_de_passe_chiffre, fingerprint = self.certificat_maitredescles.chiffrage_asymmetrique(self.mot_de_passe.encode('utf-8'))

        requete_cle_racine = {
            'fingerprint': '',
            'mot_de_passe_chiffre': str(b64encode(mot_de_passe_chiffre), 'utf-8'),
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cle_racine,
            'millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_CLE_RACINE,
            'abcd-1234',
            self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_cle_backup(self):
        requete_cert_maitredescles = {
            'certificat': self.certificat_courant_pem,
            'domaine': 'Topologie',
            'identificateurs_document': {
                'transactions_nomfichier': 'Topologie_transactions_2020100323_3.protege.jsonl.xz.mgs1',
            },
            "cles": {
                "cGrSTYhEB19QGjiipURder6/IRc=Z": "aVA+CkgvSqP496IBrDbFa2SVP11f+BKq8oc3vJ2+8g4Ypo4u2c5ZnYvNPTFEnoAGcggGRDDQY2wkCNUGOjh2gTMnItUOdWJNq5vmjs0XNTOpiEkJpq7U5ZzPTssn2m6V1JbG0TmTu5/f24K1HAhae2lz95mlVdwufm+kQolwL5rzULOzGGV+mX8PGuaQkCHPdcletVj9IUwgkwrwYAgjYHt9qPjGUHO7Bcyiw1t7dWTUTbvt59uh41J53IB79hRqwx8BMeY7rMsWoY5ffVIWBorV//XxcsnEqiXgEOUJoC/LmQfI21FxPNV6mBIzs4hakvOgET5D2yGoAlYX4wJnxg==",
                "OaUo6vkTDQ26S9hbdFqeKYS3NyI=": "jYYDIgn4ShniCGkBgfJ1tIzOARRl1wBAps/SQwKBDMZnL+uH3MAhsieg6XW5vtdZyC/hh+hZ2q++2GGsgSUHAKbJlTn8YWS4WuRpUQssg4agpfCVPndkRoN1qf7QaQiN27HZJhMawqif0KDx7ZU0MsJoHF1l0X0E+frNuVg+WY+8DpHRxxc15CeHcLToSYn1V15WDiCTbrfvZ0zONEF2btie7eQ/B81prcTnUNrJe5xoHraEaQOcD4NOW1gCV0D8YfGcKZ2/by9zad3aJL5iUvGW4AeftewOaaKu4tM5bjdqSeICoeaI0fXwk7L/q2bBR2FOMM/P4so3JbabOaShHA=="
            },
            "iv": "16ldjBWXospiToJEKEIWGw==",
        }

        print(requete_cert_maitredescles)

        self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_DECHIFFRAGE_BACKUP,
            'abcd-1234',
            self.queue_name
        )

    def requete_cle_backup_application(self):
        requete_cert_maitredescles = {
            'certificat': self.certificat_courant_pem,
            'identificateurs_document': {
                'archive_nomfichier': 'application_mariadb_redmine_client_archive_202010101721.tar.xz.mgs1'
            },
        }

        print(requete_cert_maitredescles)

        self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_DECHIFFRAGE_BACKUP,
            'abcd-1234',
            self.queue_name
        )

    def commande_sauvegarder_cle(self):
        commande = {
            'domaine': 'Topologie',
            'identificateurs_document': {
                'transactions_nomfichier': 'Topologie_transactions_2020100325_3.protege.jsonl.xz.mgs1',
            },
            "cles": {
                # "cGrSTYhEB19QGjiipURder6/IRc=Z": "aVA+CkgvSqP496IBrDbFa2SVP11f+BKq8oc3vJ2+8g4Ypo4u2c5ZnYvNPTFEnoAGcggGRDDQY2wkCNUGOjh2gTMnItUOdWJNq5vmjs0XNTOpiEkJpq7U5ZzPTssn2m6V1JbG0TmTu5/f24K1HAhae2lz95mlVdwufm+kQolwL5rzULOzGGV+mX8PGuaQkCHPdcletVj9IUwgkwrwYAgjYHt9qPjGUHO7Bcyiw1t7dWTUTbvt59uh41J53IB79hRqwx8BMeY7rMsWoY5ffVIWBorV//XxcsnEqiXgEOUJoC/LmQfI21FxPNV6mBIzs4hakvOgET5D2yGoAlYX4wJnxg==",
                "OaUo6vkTDQ26S9hbdFqeKYS3NyI=": "jYYDIgn4ShniCGkBgfJ1tIzOARRl1wBAps/SQwKBDMZnL+uH3MAhsieg6XW5vtdZyC/hh+hZ2q++2GGsgSUHAKbJlTn8YWS4WuRpUQssg4agpfCVPndkRoN1qf7QaQiN27HZJhMawqif0KDx7ZU0MsJoHF1l0X0E+frNuVg+WY+8DpHRxxc15CeHcLToSYn1V15WDiCTbrfvZ0zONEF2btie7eQ/B81prcTnUNrJe5xoHraEaQOcD4NOW1gCV0D8YfGcKZ2/by9zad3aJL5iUvGW4AeftewOaaKu4tM5bjdqSeICoeaI0fXwk7L/q2bBR2FOMM/P4so3JbabOaShHA=="
            },
            "iv": "16ldjBWXospiToJEKEIWGw==",
            'domaine_action_transaction': ConstantesMaitreDesCles.TRANSACTION_NOUVELLE_CLE_BACKUPTRANSACTIONS,
        }

        self.generateur.transmettre_commande(
            commande,
            'commande.MaitreDesCles.%s' % ConstantesMaitreDesCles.COMMANDE_SAUVEGARDER_CLE,
            exchange=Constantes.SECURITE_SECURE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name
        )

    def commande_signer_cle_backup(self):
        with open ('/home/mathieu/mgdev/certs/pki.connecteur.key', 'rb') as fichier:
            key_bytes = fichier.read()

        enveloppe = EnveloppeCleCert()
        enveloppe.key_from_pem_bytes(key_bytes, None)
        public_bytes = enveloppe.public_bytes

        requete_cle_racine = {
            'cle_publique': public_bytes.decode('utf-8'),
        }
        enveloppe_requete = self.generateur.transmettre_commande(
            requete_cle_racine,
            'commande.millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.COMMANDE_SIGNER_CLE_BACKUP,
            correlation_id='abcd-1234',
            reply_to=self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def commande_restaurer_backup_cle(self):
        with open ('/home/mathieu/mgdev/certs/pki.connecteur.key', 'rb') as fichier:
            key_bytes = fichier.read()

        clecert = EnveloppeCleCert()
        clecert.key_from_pem_bytes(key_bytes, None)
        clecert.password = self.mot_de_passe.encode('utf-8')
        key_chiffree_bytes = clecert.private_key_bytes

        self.cert_maitredescles_recu.wait(5)
        mot_de_passe_chiffre, fingerprint = self.certificat_maitredescles.chiffrage_asymmetrique(self.mot_de_passe.encode('utf-8'))

        enveloppe = EnveloppeCleCert()
        enveloppe.key_from_pem_bytes(key_bytes, None)

        requete_cle_racine = {
            'cle_privee': key_chiffree_bytes.decode('utf-8'),
            'mot_de_passe_chiffre': str(b64encode(mot_de_passe_chiffre), 'utf-8'),
            # 'fingerprint_base64': 'Ut/UQ5aKomoGzXB7mpUduPk4Xzg=',
        }
        enveloppe_requete = self.generateur.transmettre_commande(
            requete_cle_racine,
            'commande.millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.COMMANDE_RESTAURER_BACKUP_CLES,
            correlation_id='abcd-1234',
            reply_to=self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def commande_creer_cles_millegrille_hebergee(self):
        enveloppe_requete = self.generateur.transmettre_commande(
            dict(),
            'commande.millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.COMMANDE_CREER_CLES_MILLEGRILLE_HEBERGEE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.DEFAUT_MQ_EXCHANGE_MIDDLEWARE
        )

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def nouvelle_cle_grosfichiers(self):

        cle_secrete = 'Mon mot de passe secret'
        clecert_chiffrage = self.clecert_millegrille
        # cert_chiffrage = self.certificat_courant
        cert_chiffrage = clecert_chiffrage.cert
        fingerprint_b64 = clecert_chiffrage.fingerprint_b64
        cle_secrete_encryptee = cert_chiffrage.public_key().encrypt(
            cle_secrete.encode('utf8'),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        cle_secrete_encryptee_base64 = b64encode(cle_secrete_encryptee).decode('utf8')

        nouvelle_cle = {
            "domaine": "GrosFichiers",
            ConstantesMaitreDesCles.TRANSACTION_CHAMP_IDENTIFICATEURS_DOCUMENTS: {
                "fuuid": str(uuid4()),
            },
            "cles": {fingerprint_b64: cle_secrete_encryptee_base64},
            "iv": "gA8cRaiJE+8aN2c6/N1vTg==",
            "sujet": ConstantesMaitreDesCles.DOCUMENT_LIBVAL_CLES_GROSFICHIERS,
        }

        enveloppe_val = self.generateur.soumettre_transaction(
            nouvelle_cle,
            ConstantesMaitreDesCles.TRANSACTION_NOUVELLE_CLE_GROSFICHIER,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def nouvelle_cle_document(self):

        fingerprint_b64 = self.clecert.fingerprint_b64
        cle_secrete = 'Mon mot de passe secret'
        cle_secrete_encryptee = self.certificat_courant.public_key().encrypt(
            cle_secrete.encode('utf8'),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        cle_secrete_encryptee_mime64 = b64encode(cle_secrete_encryptee).decode('utf8')

        nouvelle_cle = {
            "domaine": "MaitreDesComptes",
            ConstantesMaitreDesCles.TRANSACTION_CHAMP_IDENTIFICATEURS_DOCUMENTS: {
                "_mg-libelle": "proprietaire",
                "champ": 'dummy' + str(uuid4()),
            },
            "cles": {fingerprint_b64: cle_secrete_encryptee_mime64},
            "iv": "gA8cRaiJE+8aN2c6/N1vTg==",
        }

        enveloppe_val = self.generateur.soumettre_transaction(
            nouvelle_cle,
            ConstantesMaitreDesCles.TRANSACTION_NOUVELLE_CLE_DOCUMENT,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def nouvelle_cle_backup(self):
        cle_secrete = 'Mon mot de passe secret'
        clecert_chiffrage = self.clecert_millegrille
        # cert_chiffrage = self.certificat_courant
        cert_chiffrage = clecert_chiffrage.cert
        fingerprint_b64 = clecert_chiffrage.fingerprint_b64
        cle_secrete_encryptee = cert_chiffrage.public_key().encrypt(
            cle_secrete.encode('utf8'),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        cle_secrete_encryptee_base64 = b64encode(cle_secrete_encryptee).decode('utf8')

        date_str = datetime.datetime.utcnow().strftime('%y%m%d%h%m')

        nouvelle_cle = {
            "domaine": "Topologie",
            ConstantesMaitreDesCles.TRANSACTION_CHAMP_IDENTIFICATEURS_DOCUMENTS: {
                "transactions_nomfichier": "Topologie_transactions_%s_3.protege.jsonl.xz.mgs1" % date_str,
            },
            "cles": {fingerprint_b64: cle_secrete_encryptee_base64},
            "iv": "gA8cRaiJE+8aN2c6/N1vTg==",
            "sujet": ConstantesMaitreDesCles.DOCUMENT_LIBVAL_CLES_BACKUPTRANSACTIONS,
        }

        enveloppe_val = self.generateur.soumettre_transaction(
            nouvelle_cle,
            ConstantesMaitreDesCles.TRANSACTION_NOUVELLE_CLE_BACKUPTRANSACTIONS,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_declasser_grosfichier(self):

        transaction = {
            'fuuid': '3830311b-145f-4ab2-850e-f4defdb70767'
        }

        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesMaitreDesCles.TRANSACTION_DECLASSER_CLE_GROSFICHIER,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_signer_certificat_navigateur(self):

        public_key_str = """
-----BEGIN CERTIFICATE REQUEST-----
MIICfTCCAWUCAQAwODESMBAGA1UEAxMJbm9tVXNhZ2VyMRMwEQYDVQQLEwpOYXZp
Z2F0ZXVyMQ0wCwYDVQQKEwRpZG1nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAwDlWi2KJsccrDJKHq8xLYjCqndu+Oh4GNsbRypPctuu+oU6PNkwwjSIN
xNuJret+ZVr2mw2MNbt9JYANriltYwvFWkF63NTIGXstaegNCkj6vqa4KdtXK7uu
NREtMLEhEu+ZWYcR2hWzVEN9GyIPwEgPNYQwUjjjLADUnaZ73t9Bk+fivgll0JbJ
reSw8DHqvdcmB28AnXltch6Wh34EGiYPbJqDm+NnCHHZ2EumbPRkN5/bqZTmpUDw
qqt+6cTcgAtdIuzYm3sPQt/Zf3EJwDT9dBxVrdbBnNFG4js3lauy49hog78zwwNP
/i3DZU3VDDCDeT4POKfEHXtwxTLF4QIDAQABoAAwDQYJKoZIhvcNAQENBQADggEB
AKBdiHJamlXfevloSBhehrf5g7lRbISGEsyY5HOXvVMLbip75QcGMcz8jnEJxYFk
8mDPuxlR3VOkyDiPGpLloN9hOgk50igwtRmFXcGCENbaJX2FZdho0yyx/yS03WXR
HXkje/v1Z6x1gitAxACbvvywo4qtIQoBSwP08D0JIGtD2GWPvzd1+PSgsdqQsmxz
EMkpLW0RZ2y1fCZyXbXPfAI4rnCL5Lb3CW7e4sbdH2XkcV4fBPEDGo03TE8648XV
6PCY9G7vw3iPiAhicMp1nI9bx+N/IapZvWmqR8vOURfFHYB1ilnli7S3MNXpDC9Q
BMz4ginADdtNs9ARr3DcwG4=
-----END CERTIFICATE REQUEST-----
        """

        commande = {
            'est_proprietaire': True,
            'csr': public_key_str,
        }

        enveloppe_val = self.generateur.transmettre_commande(
            commande,
            'commande.MaitreDesCles.' + ConstantesMaitreDesCles.COMMANDE_SIGNER_NAVIGATEUR_CSR,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_demande_inscription_tierce(self):
        transaction = {
            'idmg': '33KRMhqcWCKvMHyY5xymMCUEbT53Kg1NqUb9AU6'
        }
        domaine = ConstantesMaitreDesCles.TRANSACTION_GENERER_DEMANDE_INSCRIPTION

        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            domaine,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_signature_inscription_tierce(self):
        with open('/home/mathieu/PycharmProjects/MilleGrilles.consignation.python/test/messages/demande_connexion.json') as fichier:
            transaction = json.load(fichier)
        domaine = ConstantesMaitreDesCles.TRANSACTION_GENERER_CERTIFICAT_POUR_TIERS

        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            domaine,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_supprimer_trousseau_hebergement(self):
        domaine = ConstantesMaitreDesCles.TRANSACTION_HEBERGEMENT_SUPPRIMER

        enveloppe_val = self.generateur.soumettre_transaction(
            {'idmg': '3M87pZxVVWbT1dVLeRarQnge1mvADTs4trG7Caa'},
            domaine,
            reply_to=self.queue_name,
            correlation_id='efgh'
        )

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def commande_signer_csr(self):
        clecert = EnveloppeCleCert()
        clecert.generer_private_key(generer_password=True, keysize=4096)

        public_key = clecert.private_key.public_key()
        builder = x509.CertificateSigningRequestBuilder()
        name = x509.Name([
            x509.NameAttribute(x509.name.NameOID.ORGANIZATION_NAME, '3aeGLdmMbA1BrmRYwpPgNAZKH2WGWmSedBjKSxw'),
            x509.NameAttribute(x509.name.NameOID.ORGANIZATIONAL_UNIT_NAME, 'domaines'),
            x509.NameAttribute(x509.name.NameOID.COMMON_NAME, 'test')
        ])
        builder = builder.subject_name(name)
        request = builder.sign(
            clecert.private_key, hashes.SHA256(), default_backend()
        )
        request_pem = request.public_bytes(primitives.serialization.Encoding.PEM)

        commande = {
            'liste_csr': [request_pem.decode('utf-8')],
        }
        enveloppe_requete = self.generateur.transmettre_commande(
            commande,
            'commande.millegrilles.domaines.MaitreDesCles.%s' % ConstantesMaitreDesCles.COMMANDE_SIGNER_CSR,
            correlation_id='abcd-1234',
            reply_to=self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def commande_signer_csr_noeud_prive(self):
        clecert = EnveloppeCleCert()
        clecert.generer_private_key(keysize=2048)

        public_key = clecert.private_key.public_key()
        builder = x509.CertificateSigningRequestBuilder()
        name = x509.Name([
            # x509.NameAttribute(x509.name.NameOID.ORGANIZATION_NAME, '3aeGLdmMbA1BrmRYwpPgNAZKH2WGWmSedBjKSxw'),
            x509.NameAttribute(x509.name.NameOID.ORGANIZATIONAL_UNIT_NAME, 'intermediaire'),
            x509.NameAttribute(x509.name.NameOID.COMMON_NAME, str(uuid4()))
        ])
        builder = builder.subject_name(name)
        request = builder.sign(
            clecert.private_key, hashes.SHA256(), default_backend()
        )
        request_pem = request.public_bytes(primitives.serialization.Encoding.PEM)

        commande = {
            'liste_csr': [request_pem.decode('utf-8')],
            'role': 'prive'
        }
        enveloppe_requete = self.generateur.transmettre_commande(
            commande,
            'commande.MaitreDesCles.%s' % ConstantesMaitreDesCles.COMMANDE_SIGNER_CSR,
            correlation_id='abcd-1234',
            reply_to=self.queue_name
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_cles_non_dechiffrables(self):
        requete_cle_racine = {
            'taille': 2
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cle_racine,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_CLES_NON_DECHIFFRABLES,
            'abcd-1234',
            self.queue_name
        )
        return enveloppe_requete

    def requete_cles_non_dechiffrables_verifmaitrecles(self):
        self.cert_maitredescles_recu.wait(5)  # Attendre reception cert maitredescles

        # Prendre le fingerprint du cert maitre des cles - devrait retourner 0 cles non chiffrees
        fingerprint_maitrecles = self.certificat_maitredescles.fingerprint_b64

        requete_cle_racine = {
            'taille': 2,
            'fingerprints_actifs': [fingerprint_maitrecles],
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cle_racine,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_CLES_NON_DECHIFFRABLES,
            'abcd-1234',
            self.queue_name
        )
        return enveloppe_requete

    def requete_cles_non_dechiffrables_verifcledummy(self):
        self.cert_maitredescles_recu.wait(5)  # Attendre reception cert maitredescles

        # Prendre le fingerprint du cert maitre des cles - devrait retourner 0 cles non chiffrees
        fingerprint_maitrecles = self.certificat_maitredescles.fingerprint_b64

        requete_cle_racine = {
            'taille': 2,
            'fingerprints_actifs': ['DUMMY'],
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cle_racine,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_CLES_NON_DECHIFFRABLES,
            'abcd-1234',
            self.queue_name
        )
        return enveloppe_requete

    def requete_compter_cles_non_dechiffrables_verifcledummy(self):
        self.cert_maitredescles_recu.wait(5)  # Attendre reception cert maitredescles

        # Prendre le fingerprint du cert maitre des cles - devrait retourner 0 cles non chiffrees
        fingerprint_maitrecles = self.certificat_maitredescles.fingerprint_b64

        requete_cle_racine = {
            # 'fingerprints_actifs': ['DUMMY'],
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cle_racine,
            'MaitreDesCles.%s' % ConstantesMaitreDesCles.REQUETE_COMPTER_CLES_NON_DECHIFFRABLES,
            'abcd-1234',
            self.queue_name
        )
        return enveloppe_requete

    def executer(self):
        # self.event_recu.wait(5)
        # self.event_recu.clear()

        # enveloppe = self.requete_cert_maitredescles()
        # self.requete_trousseau_hebergement()

        # for i in range(0, 2):
        #     self.nouvelle_cle_grosfichiers()
        #     self.nouvelle_cle_document()
        #     self.nouvelle_cle_backup()

        # enveloppe = self.transaction_declasser_grosfichier()
        # enveloppe = self.transaction_signer_certificat_navigateur()
        # enveloppe = self.requete_decryptage_cle_fuuid()
        # enveloppe = self.requete_decryptage_cle_fuuid_avecfingerprint()
        # self.transaction_demande_inscription_tierce()
        # self.transaction_signature_inscription_tierce()
        # self.transaction_supprimer_trousseau_hebergement()
        # self.requete_cle_document()

        # self.requete_cle_racine()
        # self.commande_signer_cle_backup()
        # self.commande_restaurer_backup_cle()
        # self.commande_creer_cles_millegrille_hebergee()
        # self.commande_signer_csr()
        # self.commande_signer_csr_noeud_prive()

        # self.requete_cles_non_dechiffrables()
        # self.requete_cles_non_dechiffrables_verifmaitrecles()
        # self.requete_cles_non_dechiffrables_verifcledummy()
        self.requete_compter_cles_non_dechiffrables_verifcledummy()
Example #19
0
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.fichier_fuuid = "39c1e1b0-b6ee-11e9-b0cd-d30e8fab842j"

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(json.dumps(json.loads(body.decode('utf-8')), indent=4))
        print("Channel : " + str(ch))
        print("Method : " + str(method))
        print("Properties : " + str(properties))
        print("Channel virtual host : " +
              str(ch.connection.params.virtual_host))

    def requete_cert_fingerprint(self):
        requete_cert = {
            'fingerprint': 'fe4e7c9b64a4f2f31b7f8c54102573d14c8894d0'
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert,
            ConstantesPki.REQUETE_CERTIFICAT_DEMANDE,
            'abcd-1234',
            self.queue_name,
            securite=Constantes.SECURITE_PROTEGE,
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_cert_backup(self):
        requete_cert = {}
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert,
            '%s.%s' % (ConstantesPki.DOMAINE_NOM,
                       ConstantesPki.REQUETE_CERTIFICAT_BACKUP),
            'abcd-1234',
            self.queue_name,
            securite=Constantes.SECURITE_PROTEGE,
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def renouveller_certs_docker(self):
        requete_cert = {
            'altdomains': {
                "mq": 'mq.maple.maceroc.com,mg-dev3.maple.maceroc.com'
            },
            'roles': ['mq'],
        }
        enveloppe_requete = self.generateur.soumettre_transaction(
            requete_cert,
            ConstantesPki.TRANSACTION_RENOUVELLER_CERT_DOCKER,
            'abcd-1234',
            self.queue_name,
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_certificat(self):
        requete = {
            'fingerprint':
            'sha256_b64:eju05mzQkl77M9XUJgJHMJjaxaHnSHa0moGHXCl9wxE='
        }
        domaine_action = 'requete.Pki.' + ConstantesPki.REQUETE_CERTIFICAT
        self.generateur.transmettre_requete(requete,
                                            domaine_action,
                                            correlation_id='abcd',
                                            reply_to=self.queue_name)

    def executer(self):
        # self.renouveller_certs_docker()
        # self.requete_cert_backup()
        # self.requete_cert_noeuds()
        self.requete_certificat()
class MessagesSample(BaseCallback):

    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.channel = None
        self.event_recu = Event()

        self.noeud_id = '6bee12f0-9284-42dc-83a2-52d50c69de4a'

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True, exclusive=True, callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck, queue=self.queue_name, no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(json.dumps(json.loads(body.decode('utf-8')), indent=4))
        print("Channel : " + str(ch))
        print("Method : " + str(method))
        print("Properties : " + str(properties))
        print("Channel virtual host : " + str(ch.connection.params.virtual_host))

    # def installer_application_blynk(self):
    #     commande = {
    #         'nom_application': 'blynk',
    #         'configuration': blynk_app,
    #     }
    #     domaineAction = 'commande.servicemonitor.%s.%s' % (
    #         uuid_service_monitor, Constantes.ConstantesServiceMonitor.COMMANDE_INSTALLER_APPLICATION)
    #
    #     enveloppe = self.generateur.transmettre_commande(
    #         commande,
    #         domaineAction,
    #         correlation_id='abcd-1234',
    #         reply_to=self.queue_name,
    #         exchange=Constantes.SECURITE_PROTEGE
    #     )
    #
    #     print("Envoi : %s" % enveloppe)
    #     return enveloppe

    def backup_application(self):
        commande = {
            # 'nom_application': 'redmine',
            'nom_application': 'blynk',
        }
        domaineAction = 'commande.servicemonitor.%s.%s' % (
            self.noeud_id, Constantes.ConstantesServiceMonitor.COMMANDE_BACKUP_APPLICATION)

        enveloppe = self.generateur.transmettre_commande(
            commande,
            domaineAction,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.SECURITE_PROTEGE
        )

        print("Envoi : %s" % enveloppe)
        return enveloppe

    def backup_applications(self):
        commande = {}
        domaineAction = Constantes.ConstantesBackup.COMMANDE_BACKUP_DECLENCHER_HORAIRE_GLOBAL

        enveloppe = self.generateur.transmettre_commande(
            commande,
            domaineAction,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.SECURITE_PROTEGE
        )

        print("Envoi : %s" % enveloppe)
        return enveloppe

    def restore_application(self):
        commande = {
            'nom_application': 'redmine_mariadb',
            # 'archive_tarfile': '/tmp/monitorbackup/mariadb_redmine_client.0.tar',
        }
        domaineAction = 'commande.servicemonitor.%s.%s' % (
            self.noeud_id, Constantes.ConstantesServiceMonitor.COMMANDE_RESTORE_APPLICATION)

        enveloppe = self.generateur.transmettre_commande(
            commande,
            domaineAction,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.SECURITE_PROTEGE
        )

        print("Envoi : %s" % enveloppe)
        return enveloppe

    def executer(self):
        self.backup_application()
Example #21
0
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.uuid_blogpost = '3c38abee-3d68-11ea-be1a-00155d011f09'

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(body)

    def maj_blogpost(self):
        transaction = {
            "titre": "title blogpost",
            "titre_fr": "Titre blogpost",
            "texte": "Text blogpost",
            "texte_fr": "Texte du blogpost",
            # 'uuid': self.uuid_blogpost,
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesPlume.TRANSACTION_MAJ_BLOGPOST,
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Transaction: %s" % enveloppe_val)
        return enveloppe_val

    def publier_blogpost(self):
        transaction = {'uuid': self.uuid_blogpost}
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesPlume.TRANSACTION_PUBLIER_BLOGPOST,
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Transaction: %s" % enveloppe_val)
        return enveloppe_val

    def retirer_blogpost(self):
        transaction = {'uuid': self.uuid_blogpost}
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesPlume.TRANSACTION_RETIRER_BLOGPOST,
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Transaction: %s" % enveloppe_val)
        return enveloppe_val

    def supprimer_blogpost(self):
        transaction = {'uuid': self.uuid_blogpost}
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesPlume.TRANSACTION_SUPPRIMER_BLOGPOST,
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Transaction: %s" % enveloppe_val)
        return enveloppe_val

    def executer(self):
        sample.maj_blogpost()
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.fichier_fuuid = "39c1e1b0-b6ee-11e9-b0cd-d30e8fab842j"

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        reponse = json.loads(body.decode('utf-8'))
        print(json.dumps(reponse, indent=2))

    def transaction_nouvelle_version_metadata(self):
        transaction = {
            'nom_fichier':
            'Bill Morneau resigns as finance minister and MP, will seek to lead OECD.pdf',
            'securite':
            '3.protege',
            'fuuid':
            str(uuid4()),
            'mimetype':
            'image/blarghs',
            'taille':
            1190698,
            'hachage':
            'sha512_b64:ONOJGqswORDLwxeB/82dewqx2kAyOD0k3YQkipbkCBt3CyYAqk6BwAPw+sAFLo8BmRmLvNGlpmnnuFPs0hAmfg==',
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_NOUVELLEVERSION_METADATA,
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Envoi metadata: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_nouvelle_version_transfertcomplete(self):
        transaction = {
            "fuuid":
            self.fichier_fuuid,
            "sha256":
            "739291ef2f7f3e0f945712112df9a62aeb2642d3828551f9fa3c95449a415e30",
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.nouvelleVersion.transfertComplete',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Envoi transfert complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_renommer_document(self):
        transaction = {
            "uuid": "ea1e1a37-14ef-46f4-8a75-021850e0630a",
            "nom": 'Bashir Bouzouka 3!.jpg',
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_RENOMMER_DOCUMENT,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_changer_etiquettes_fichier(self):
        transaction = {
            "uuid":
            "1385e685-0630-4372-87a0-224804dfe7fd",
            "etiquettes":
            ['efgh', '1234', 'pUBlic', '4.disseminer', 'HÉ! ayoye mé açcents']
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.changerEtiquettesFichier',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Changer libelle complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_decrire_fichier(self):
        transaction = {
            "uuid": "41548d46-c12b-41f6-b205-4c0ae7d64c16",
            # "commentaires": "J'ai un commentaire. Ye! Pis on en rajoute.",
            "titre": {
                'en': 'Name in English',
                'fr': 'Nom en francais'
            },
            "description": {
                'en': '<p>Complete description of the file</p>',
                'fr': '<p>Description complete du fichier</p>',
            }
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'GrosFichiers.' +
            ConstantesGrosFichiers.TRANSACTION_DECRIRE_FICHIER,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_decrire_collection(self):
        transaction = {
            "uuid": "201e1fb7-66bd-4901-b52a-116c65d7b0d9",
            # "nom_collection": "public",
            "commentaires": "J'ai un commentaire. Ye! Pis on en rajoute.",
            "titre": {
                'en': 'Collection name in English',
                'fr': 'Nom de collection en francais'
            },
            "description": {
                'en': '<p>Complete description of the file</p>',
                'fr': '<p>Description complete du fichier</p>',
            },
            'securite': '1.public',
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'GrosFichiers.' +
            ConstantesGrosFichiers.TRANSACTION_DECRIRE_COLLECTION,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_supprimer_fichier(self):
        transaction = {
            ConstantesGrosFichiers.DOCUMENT_LISTE_UUIDS:
            ["53aca732-fa3c-4e21-9462-e01e5157741a"],
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_SUPPRIMER_FICHIER,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_recuperer_fichier(self):
        transaction = {
            ConstantesGrosFichiers.DOCUMENT_LISTE_UUIDS:
            ["53aca732-fa3c-4e21-9462-e01e5157741a"],
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_RECUPERER_FICHIER,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_creer_collection_vide(self):
        transaction = {}
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.nouvelleCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Complete : %s" % enveloppe_val)
        return enveloppe_val

    def transaction_creer_collection_2docs(self):
        transaction = {
            "documents": [
                {
                    'uuid': 'b63c5771-d2c8-4d5c-9db5-fdbe0a35ac36'
                },
                {
                    'uuid': 'ff754f4a-6df1-4fbc-ab64-70693c7c487f'
                },
            ]
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.nouvelleCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Complete : %s" % enveloppe_val)
        return enveloppe_val

    def transaction_renommer_collection(self):
        transaction = {
            "uuid": "0fda4ce6-0ecf-11ea-bb74-00155d011f09",
            "nom": "sous_test_change_2",
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.renommerCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_supprimer_collection(self):
        transaction = {
            "uuid": "0fda4ce6-0ecf-11ea-bb74-00155d011f09",
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.supprimerCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_recuperer_collection(self):
        transaction = {
            "uuid": "0fda4ce6-0ecf-11ea-bb74-00155d011f09",
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.recupererCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_figer_collection(self):
        transaction = {
            "uuid": "a80c39cc-16ca-11ea-9318-00155d011f09",
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.figerCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("transaction_figer_collection: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_changer_etiquettes_collection(self):
        transaction = {
            "uuid": "a80c39cc-16ca-11ea-9318-00155d011f09",
            "etiquettes": ['abcd', '1234']
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'millegrilles.domaines.GrosFichiers.changerEtiquettesCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_ajouter_fichiers_collection(self):
        transaction = {
            "uuid":
            "5edceede-f77c-11ea-8eb7-ff28b56f498d",
            ConstantesGrosFichiers.DOCUMENT_COLLECTION_DOCS_UUIDS: [
                'ab13c39c-35e4-4f60-a353-ef2b63d92c54',
            ]
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'GrosFichiers.ajouterFichiersCollection',
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_retirer_fichiers_collection(self):
        transaction = {
            ConstantesGrosFichiers.DOCUMENT_FICHIER_UUID_DOC:
            "862a4348-b85a-4ab7-8021-ca26c9bb58bf",
            ConstantesGrosFichiers.DOCUMENT_COLLECTION_DOCS_UUIDS: [
                '53aca732-fa3c-4e21-9462-e01e5157741a',
            ]
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_RETIRER_FICHIERS_COLLECTION,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Renommer repertoire complete: %s" % enveloppe_val)
        return enveloppe_val

    def transaction_changer_favoris(self):
        transaction = {
            ConstantesGrosFichiers.DOCUMENT_COLLECTION_DOCS_UUIDS: {
                'b212db7f-27f7-4d1e-bba2-5b2293e4d9ea': False,
                '2ca533be-c463-4cc3-b729-5bf34f53c623': True,
            }
        }

        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_CHANGER_FAVORIS,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Ajouter favori: %s" % enveloppe_val)
        return enveloppe_val

    def requete_activite(self):
        requete = {
            'skip': 0,
            'limit': 3,
        }

        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            Constantes.ConstantesGrosFichiers.REQUETE_ACTIVITE_RECENTE,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Activite recente %s" % enveloppe_val)
        return enveloppe_val

    def requete_corbeille(self):
        requete = {
            'skip': 0,
            'limit': 3,
        }

        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            Constantes.ConstantesGrosFichiers.REQUETE_CORBEILLE,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("Activite recente %s" % enveloppe_val)
        return enveloppe_val

    def requete_documents_collection(self):
        requete = {
            ConstantesGrosFichiers.DOCUMENT_FICHIER_UUID_DOC:
            '5edceede-f77c-11ea-8eb7-ff28b56f498d',
            'skip': 1,
            'limit': 2,
            'sort_keys': ['nom_collection', 'nom_fichier']
        }
        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            Constantes.ConstantesGrosFichiers.REQUETE_CONTENU_COLLECTION,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("requete_documents_collection %s" % enveloppe_val)
        return enveloppe_val

    def requete_documents_par_uuid(self):
        requete = {
            ConstantesGrosFichiers.DOCUMENT_LISTE_UUIDS:
            ['5edceede-f77c-11ea-8eb7-ff28b56f498d'],
        }
        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            Constantes.ConstantesGrosFichiers.REQUETE_DOCUMENTS_PAR_UUID,
            reply_to=self.queue_name,
            correlation_id='abcd')

        print("requete_documents_collection %s" % enveloppe_val)
        return enveloppe_val

    def transaction_associer_preview(self):
        transaction = {
            'uuid': 'af6606b0-fac9-11ea-af1c-37323461d64a',
            'fuuid': '40b268a7-2af4-4424-97ff-cb2a3610b7a1',
            ConstantesGrosFichiers.DOCUMENT_FICHIER_MIMETYPE_PREVIEW:
            'image/blarghs',
            ConstantesGrosFichiers.DOCUMENT_FICHIER_FUUID_PREVIEW:
            str(uuid4()),
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            ConstantesGrosFichiers.TRANSACTION_ASSOCIER_PREVIEW,
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Envoi metadata: %s" % enveloppe_val)
        return enveloppe_val

    def requete_decryptage_cle_fuuid(self):
        requete_cert_maitredescles = {
            'fuuid': "ddb0d8f0-f7b4-11ea-89ec-13126005a8b0"
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles, 'MaitreDesCles.%s' %
            Constantes.ConstantesMaitreDesCles.REQUETE_DECRYPTAGE_GROSFICHIER,
            'abcd-1234', self.queue_name)

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_permission_dechiffrage_fichier_public(self):
        requete_cert_maitredescles = {
            # 'fuuid': 'd2f5ebf0-228c-11eb-b2e0-e1493ef37733',
            'fuuid': 'd0fa9123-228c-11eb-8f98-5d3582e42c8c',
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles, 'GrosFichiers.' + Constantes.
            ConstantesGrosFichiers.REQUETE_PERMISSION_DECHIFFRAGE_PUBLIC,
            'abcd-1234', self.queue_name)

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_permission_decryptage_cle_fuuid(self):
        # mq_cert = self.configuration.mq_certfile
        # with open(mq_cert, 'r') as fichier:
        #     mq_certfile = fichier.read()

        signateur = self.contexte.signateur_transactions
        certs = signateur.chaine_certs

        # certs = signateur.split_chaine_certificats(mq_certfile)

        requete_cert_maitredescles = {
            'fuuid': "d0fa9123-228c-11eb-8f98-5d3582e42c8c",
            'fuuid_preview': "d2f5ebf0-228c-11eb-b2e0-e1493ef37733",
            'roles_permis': ['domaines'],
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles,
            'MaitreDesCles.%s' %
            Constantes.ConstantesMaitreDesCles.REQUETE_DECRYPTAGE_GROSFICHIER,
            'abcd-1234',
            self.queue_name,
            ajouter_certificats=True)

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_collections_publiques(self):
        requete = {}
        self.generateur.transmettre_requete(
            requete,
            'GrosFichiers.' +
            Constantes.ConstantesMaitreDesCles.REQUETE_COLLECTIONS_PUBLIQUES,
            'abcd-1234',
            self.queue_name,
            ajouter_certificats=True)

    def requete_detail_collections_publiques(self):
        requete = {}
        self.generateur.transmettre_requete(
            requete,
            'GrosFichiers.' + Constantes.ConstantesGrosFichiers.
            REQUETE_DETAIL_COLLECTIONS_PUBLIQUES,
            'abcd-1234',
            self.queue_name,
            ajouter_certificats=True)

    def commande_regenerer_previews(self):
        requete = {}
        self.generateur.transmettre_commande(
            requete,
            'commande.GrosFichiers.' +
            Constantes.ConstantesGrosFichiers.COMMANDE_REGENERER_PREVIEWS,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

    def requete_fichier_par_fuuid(self):
        requete_cert_maitredescles = {
            'fuuid': '3a4ad9e0-3af3-11eb-8020-63f97e3a189c',
        }
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert_maitredescles, 'GrosFichiers.' +
            Constantes.ConstantesGrosFichiers.REQUETE_DOCUMENT_PAR_FUUID,
            'abcd-1234', self.queue_name)

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def commande_transcoder_video(self):
        requete = {'fuuid': '45342220-3bc6-11eb-9405-f97484a4f21f'}
        self.generateur.transmettre_commande(
            requete,
            'commande.GrosFichiers.' +
            Constantes.ConstantesGrosFichiers.COMMANDE_TRANSCODER_VIDEO,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

    def executer(self):
        # enveloppe = sample.requete_profil_usager()

        # enveloppe1 = sample.transaction_nouvelle_version_metadata()
        # enveloppe2 = sample.transaction_nouvelle_version_transfertcomplete()
        # enveloppe6 = sample.transaction_renommer_fichier()
        # enveloppe11 = sample.transaction_commenter_fichier()
        # enveloppe8 = sample.transaction_changer_etiquettes_fichier()
        # enveloppe = sample.transaction_supprimer_fichier()
        # enveloppe = sample.transaction_recuperer_fichier()

        # enveloppe3 = sample.transaction_creer_collection_vide()
        # enveloppe3 = sample.transaction_creer_collection_2docs()
        # enveloppe4 = sample.transaction_renommer_collection()
        # enveloppe7 = sample.transaction_ajouter_fichiers_collection()
        # enveloppe7 = sample.transaction_retirer_fichiers_collection()
        # enveloppe = sample.transaction_changer_etiquettes_collection()
        # enveloppe5 = sample.transaction_figer_collection()
        # enveloppe5 = sample.transaction_supprimer_collection()
        # enveloppe5 = sample.transaction_recuperer_collection()

        # enveloppe = sample.transaction_changer_favoris()

        # enveloppe1 = sample.transaction_nouvelle_version_metadata()
        # enveloppe = sample.requete_activite()
        # enveloppe = sample.requete_corbeille()
        # enveloppe = sample.requete_documents_collection()
        # enveloppe = sample.requete_documents_par_uuid()
        # enveloppe = sample.transaction_associer_preview()
        # sample.requete_decryptage_cle_fuuid()
        # sample.requete_permission_decryptage_cle_fuuid()
        # sample.transaction_renommer_document()
        # sample.transaction_decrire_fichier()
        # sample.transaction_decrire_collection()
        # sample.requete_permission_dechiffrage_fichier_public()
        # sample.requete_collections_publiques()
        # sample.requete_detail_collections_publiques()
        # sample.commande_regenerer_previews()
        # sample.requete_fichier_par_fuuid()
        sample.commande_transcoder_video()

        pass
Example #23
0
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.queue_name = None

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        message = json.loads(str(body, 'utf-8'))
        print(json.dumps(message, indent=4))

    def transmettre_maj_profil_usager(self):
        fiche = {
            ConstantesPrincipale.LIBELLE_NOM: 'DugreAB',
            ConstantesPrincipale.LIBELLE_PRENOM: 'Mathieu',
            ConstantesPrincipale.LIBELLE_COURRIEL: '*****@*****.**',
            ConstantesPrincipale.LIBELLE_TWITTER: '@moi!',
        }

        domaine = ConstantesPrincipale.TRANSACTION_ACTION_MAJ_PROFILUSAGER
        enveloppe_val = self.generateur.soumettre_transaction(
            fiche, domaine, reply_to=self.queue_name, correlation_id='abcd')

        print("Envoi maj profil usager: %s" % enveloppe_val)
        return enveloppe_val

    def transmettre_maj_profil_millegrille(self):
        fiche = {
            ConstantesPrincipale.LIBELLE_NOM_MILLEGRILLE: 'Deux Tests',
            ConstantesPrincipale.LIBELLE_LANGUE_PRINCIPALE: 'fr',
            ConstantesPrincipale.LIBELLE_LANGUE_MULTILINGUE: False,
        }

        domaine = ConstantesPrincipale.TRANSACTION_ACTION_MAJ_PROFILMILLEGRILLE
        enveloppe_val = self.generateur.soumettre_transaction(
            fiche, domaine, reply_to=self.queue_name, correlation_id='abcd')

        print("Envoi maj profil usager: %s" % enveloppe_val)
        return enveloppe_val

    def requete_profil_usager(self):
        requete_profil = {
            'filtre': {
                Constantes.DOCUMENT_INFODOC_LIBELLE:
                ConstantesPrincipale.LIBVAL_PROFIL_USAGER,
            }
        }
        requetes = {'requetes': [requete_profil]}
        enveloppe_requete = self.generateur.transmettre_requete(
            requetes, 'millegrilles.domaines.Principale', 'abcd-1234',
            self.queue_name)

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def envoyer_empreinte(self):

        empreinte = {'cle': 'absfoijfdosijfds'}

        enveloppe_val = self.generateur.soumettre_transaction(
            empreinte,
            'millegrilles.domaines.Principale.creerEmpreinte',
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def ajouter_token(self):

        token = {'cle': 'cle_3'}

        enveloppe_val = self.generateur.soumettre_transaction(
            token,
            'millegrilles.domaines.Principale.ajouterToken',
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Sent: %s" % enveloppe_val)
        return enveloppe_val

    def requete_authinfo(self):
        requete_cert = {}
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert,
            ConstantesPrincipale.REQUETE_AUTHINFO_MILLEGRILLE,
            'abcd-1234',
            self.queue_name,
            securite=Constantes.SECURITE_PROTEGE,
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_infoproprietaire(self):
        requete_cert = {}
        enveloppe_requete = self.generateur.transmettre_requete(
            requete_cert,
            'requete.MaitreDesComptes.infoProprietaire',
            'abcd-1234',
            self.queue_name,
            securite=Constantes.SECURITE_PROTEGE,
        )

        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def executer(self):
        # sample.transmettre_maj_profil_usager()
        # sample.transmettre_maj_profil_millegrille()

        # sample.requete_authinfo()
        sample.requete_infoproprietaire()
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)
        self.channel = None
        self.event_recu = Event()
        # self.thread_ioloop = Thread(target=self.run_ioloop)

        self.queue_name = None

        self.certificat_maitredescles = None
        self.cert_maitredescles_recu = Event()

        self.mot_de_passe = 'sjdpo-1824-JWAZ'

        # Charger cert MaitreDesCles pour pouvoir crypter contenu a transmettre
        with open('/home/mathieu/mgdev/certs/pki.maitrecles.cert',
                  'rb') as certificat_pem:
            certificat_courant_pem = certificat_pem.read()
            cert = x509.load_pem_x509_certificate(certificat_courant_pem,
                                                  backend=default_backend())
            self.certificat_courant = cert
            self.certificat_courant_pem = certificat_courant_pem.decode('utf8')

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open)

    def queue_open(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    # def run_ioloop(self):
    #     self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(body)

        message_dict = json.loads(body)
        certificat_pem = message_dict.get('certificat')
        if certificat_pem is not None:
            cert = EnveloppeCleCert()
            cert.cert_from_pem_bytes(certificat_pem.encode('utf-8'))
            self.certificat_maitredescles = cert
            self.cert_maitredescles_recu.set()
        else:
            self.event_recu.set()
            print(json.dumps(message_dict, indent=4))

    def commande_ajouter_compte(self):
        certificat = self.certificat_courant_pem

        header = '-----BEGIN CERTIFICATE-----\n'

        certificats = certificat.split(header)[1:]
        certificats = [header + cert for cert in certificats]

        print("Transmettre certificat :\n" + certificats[0])
        for cert in certificats[1:]:
            print(cert)

        enveloppe_requete = self.generateur.transmettre_commande(
            {
                'certificat': certificats[0],
                'chaine': certificats[1:]
            },
            'commande.%s' %
            Constantes.ConstantesServiceMonitor.COMMANDE_AJOUTER_COMPTE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.DEFAUT_MQ_EXCHANGE_MIDDLEWARE)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def commande_activer_hebergement(self):
        enveloppe_requete = self.generateur.transmettre_commande(
            {},
            'commande.%s' %
            Constantes.ConstantesServiceMonitor.COMMANDE_ACTIVER_HEBERGEMENT,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def commande_desactiver_hebergement(self):
        enveloppe_requete = self.generateur.transmettre_commande(
            {},
            'commande.%s' % Constantes.ConstantesServiceMonitor.
            COMMANDE_DESACTIVER_HEBERGEMENT,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def executer(self):
        # self.commande_creer_millegrille_hebergee()
        # self.transaction_desactiver_millegrille_hebergee()
        # self.transaction_activer_millegrille_hebergee()
        # self.commande_ajouter_compte()
        self.commande_activer_hebergement()
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.fichier_fuuid = "39c1e1b0-b6ee-11e9-b0cd-d30e8fab842j"

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(json.dumps(json.loads(body.decode('utf-8')), indent=4))
        print("Channel : " + str(ch))
        print("Method : " + str(method))
        print("Properties : " + str(properties))
        print("Channel virtual host : " +
              str(ch.connection.params.virtual_host))

    def transmettre_transaction_lecture(self):
        transaction = {
            "avg":
            1.31,
            "lectures": [{
                "timestamp": 1597950486,
                "valeur": 31.4
            }, {
                "timestamp": 1597950491,
                "valeur": 5.3
            }, {
                "timestamp": 1597953581,
                "valeur": -0.4
            }, {
                "timestamp": 1597953586,
                "valeur": 38.9
            }, {
                "timestamp": 1597953591,
                "valeur": 42.2
            }, {
                "timestamp": 1597953596,
                "valeur": -49.3
            }],
            "max":
            49.9,
            "min":
            -49.6,
            "noeud_id":
            "001a12f5-e89d-4ff8-b6ac-f2ee269b9516",
            "senseur":
            "dummy/temperature",
            "timestamp":
            1597950000,
            "timestamp_max":
            1597953596,
            "timestamp_min":
            1597950491,
            "type":
            "temperature",
            "uuid_senseur":
            "7a2764fa-c457-4f25-af0d-0fc915439b21"
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            'SenseursPassifs.lecture',
            reply_to=self.queue_name,
            correlation_id='efgh')

        print("Envoi metadata: %s" % enveloppe_val)
        return enveloppe_val

    def transmettre_maj_noeud(self):
        transaction = {
            "noeud_id": "f9f3e995-f52c-4718-8e5c-a1efd101f402",
            # "securite": "2.prive",
            "securite": "2.prive",
            "blynk_host": "blynk",
            "blynk_port": 9444,
            "blynk_auth": "ciyZXHGed6Z31xtszjDpsifqPxobzEJ4"
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            SenseursPassifsConstantes.TRANSACTION_MAJ_NOEUD,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def transmettre_maj_senseur(self):
        transaction = {
            "uuid_senseur": "7a2764fa-c457-4f25-af0d-0fc915439b21",
            "securite": "2.prive",
            "senseurs": {
                "dummy/temperature": {
                    "blynk_vpin": 1
                },
                "dummy/humidite": {
                    "blynk_vpin": 2
                },
            },
        }
        enveloppe_val = self.generateur.soumettre_transaction(
            transaction,
            SenseursPassifsConstantes.TRANSACTION_MAJ_SENSEUR,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def requete_liste_noeuds(self):
        transaction = {}
        enveloppe_val = self.generateur.transmettre_requete(
            transaction,
            'SenseursPassifs.' +
            SenseursPassifsConstantes.REQUETE_LISTE_NOEUDS,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def requete_liste_senseurs_noeud(self):
        transaction = {'noeud_id': 'f9f3e995-f52c-4718-8e5c-a1efd101f402'}
        enveloppe_val = self.generateur.transmettre_requete(
            transaction,
            'SenseursPassifs.' +
            SenseursPassifsConstantes.REQUETE_LISTE_SENSEURS_NOEUD,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def executer(self):
        # sample.transmettre_transaction_lecture()
        sample.transmettre_maj_noeud()
class MessagesSample(BaseCallback):

    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.queue_name = None

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True, exclusive=True, callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck, queue=self.queue_name, no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        message = json.loads(str(body, 'utf-8'))
        print(json.dumps(message, indent=4))

    def transmettre_commande_ouverture(self, idmg):
        commande = {
            'idmg': idmg
        }

        domaine = 'commande.inter.connecter'
        enveloppe_val = self.generateur.transmettre_commande(commande, domaine, exchange=self.configuration.exchange_prive)

        print("Envoi maj fiche privee: %s" % enveloppe_val)
        return enveloppe_val

    def transmettre_requete_directe(self, idmg):
        requete = {
            'texte': 'On va se promener plus loin'
        }

        domaine = 'donne.moi.des.fichiers'
        enveloppe_val = self.generateur.transmettre_requete(requete, domaine, idmg_destination=idmg, correlation_id='moimoi')

        print("Envoi maj fiche privee: %s" % enveloppe_val)
        return enveloppe_val

    def demander_csr(self):
        domaine = 'inter.genererCsr'
        self.generateur.transmettre_requete({}, domaine, 'abcd', self.queue_name)

    def executer(self):
        idmg = 'distant'
        # enveloppe = sample.transmettre_commande_ouverture(idmg)
        # enveloppe = sample.transmettre_requete_directe(idmg)
        self.demander_csr()
Example #27
0
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)
        self.channel = None
        self.event_recu = Event()
        # self.thread_ioloop = Thread(target=self.run_ioloop)

        self.queue_name = None

        self.certificat_maitredescles = None
        self.cert_maitredescles_recu = Event()

        self.mot_de_passe = 'sjdpo-1824-JWAZ'

        # Charger cert MaitreDesCles pour pouvoir crypter contenu a transmettre
        with open('/home/mathieu/mgdev/certs/pki.maitrecles.cert',
                  'rb') as certificat_pem:
            certificat_courant_pem = certificat_pem.read()
            cert = x509.load_pem_x509_certificate(certificat_courant_pem,
                                                  backend=default_backend())
            self.certificat_courant = cert
            self.certificat_courant_pem = certificat_courant_pem.decode('utf8')

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open)

    def queue_open(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    # def run_ioloop(self):
    #     self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(body)

        message_dict = json.loads(body)
        certificat_pem = message_dict.get('certificat')
        if certificat_pem is not None:
            cert = EnveloppeCleCert()
            cert.cert_from_pem_bytes(certificat_pem.encode('utf-8'))
            self.certificat_maitredescles = cert
            self.cert_maitredescles_recu.set()
        else:
            self.event_recu.set()
            print(json.dumps(message_dict, indent=4))

    def commande_creer_millegrille_hebergee(self):
        enveloppe_requete = self.generateur.transmettre_commande(
            dict(),
            'commande.%s' %
            ConstantesHebergement.COMMANDE_CREER_MILLEGRILLE_HEBERGEE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name,
            exchange=Constantes.DEFAUT_MQ_EXCHANGE_NOEUDS)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def transaction_desactiver_millegrille_hebergee(self):
        enveloppe_requete = self.generateur.soumettre_transaction(
            {'idmg': '2zHt8UFJhAdH8XzcPfb4Evsn4kcZrvZ7fxBT97R'},
            ConstantesHebergement.TRANSACTION_DESACTIVER_MILLEGRILLE_HEBERGEE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def transaction_activer_millegrille_hebergee(self):
        enveloppe_requete = self.generateur.soumettre_transaction(
            {'idmg': '2zHt8UFJhAdH8XzcPfb4Evsn4kcZrvZ7fxBT97R'},
            ConstantesHebergement.TRANSACTION_ACTIVER_MILLEGRILLE_HEBERGEE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_millegrilles_actives(self):
        enveloppe_requete = self.generateur.transmettre_requete(
            {},
            ConstantesHebergement.REQUETE_MILLEGRILLES_ACTIVES,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        self.event_recu.clear()
        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def requete_millegrilles_hebergees(self):
        enveloppe_requete = self.generateur.transmettre_requete(
            {},
            ConstantesHebergement.REQUETE_MILLEGRILLES_HEBERGEES,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        self.event_recu.clear()
        print("Envoi requete: %s" % enveloppe_requete)
        return enveloppe_requete

    def transaction_supprimer_millegrille_hebergee(self):
        enveloppe_requete = self.generateur.soumettre_transaction(
            {'idmg': '3M87pZxVVWbT1dVLeRarQnge1mvADTs4trG7Caa'},
            ConstantesHebergement.TRANSACTION_SUPPRIMER_MILLEGRILLE_HEBERGEE,
            correlation_id='abcd-1234',
            reply_to=self.queue_name)

        print("Envoi commande: %s" % enveloppe_requete)
        return enveloppe_requete

    def executer(self):
        # self.commande_creer_millegrille_hebergee()
        # self.transaction_desactiver_millegrille_hebergee()
        # self.transaction_activer_millegrille_hebergee()
        self.requete_millegrilles_actives()
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.queue_name = None

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        message = json.loads(str(body, 'utf-8'))
        print(json.dumps(message, indent=4))

    def requete_profil_usager(self):
        requete = {'nomUsager': 'test'}
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.REQUETE_CHARGER_USAGER
        ])
        enveloppe = self.generateur.transmettre_requete(
            requete, domaine_action, 'abcd-1234', self.queue_name)

        print("Envoi : %s" % enveloppe)
        return enveloppe

    def requete_info_proprietaire(self):
        requete = {}
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.REQUETE_INFO_PROPRIETAIRE
        ])
        enveloppe = self.generateur.transmettre_requete(
            requete, domaine_action, 'abcd-1234', self.queue_name)

        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_inscrire_proprietaire(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_CLE: {
                'ma_cle': 56896,
                'autre_info': 'Da da daah'
            },
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_INSCRIRE_PROPRIETAIRE
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_inscrire_usager(self):
        transaction = {'nomUsager': 'test', 'mon_info': 237}
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_INSCRIRE_USAGER
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_maj_motdepasse(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER: 'test',
            ConstantesMaitreDesComptes.CHAMP_MOTDEPASSE: {
                'info-mot-de-passe': 1234
            },
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_MAJ_MOTDEPASSE
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_maj_motdepasse_proprietaire(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER: 'test',
            ConstantesMaitreDesComptes.CHAMP_MOTDEPASSE: {
                'info-mot-de-passe': 1234
            },
            ConstantesMaitreDesComptes.CHAMP_EST_PROPRIETAIRE: True,
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_MAJ_MOTDEPASSE
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_supprimer_motdepasse(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER: 'test',
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_SUPPRESSION_MOTDEPASSE
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_ajouter_cle(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER: 'test',
            ConstantesMaitreDesComptes.CHAMP_CLE: {
                'ma_cle': 56896,
                'autre_info': 'Da da daah'
            },
            ConstantesMaitreDesComptes.CHAMP_RESET_CLES: False,
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_AJOUTER_CLE
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_ajouter_cle_proprietaire(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_EST_PROPRIETAIRE: True,
            ConstantesMaitreDesComptes.CHAMP_CLE: {
                'ma_cle': 56896,
                'autre_info': 'Da da daah'
            },
            ConstantesMaitreDesComptes.CHAMP_RESET_CLES: False,
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_AJOUTER_CLE
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_supprimer_cles(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER: 'test',
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_SUPPRIMER_CLES
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_supprimer_usager(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER: 'test',
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_SUPPRIMER_USAGER
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_associer_idmg(self):
        transaction = {
            ConstantesMaitreDesComptes.CHAMP_NOM_USAGER:
            'test',
            Constantes.CONFIG_IDMG:
            'D_abcd1234EFGHI',
            # ConstantesMaitreDesComptes.CHAMP_CHAINE_CERTIFICAT: ['cert1', 'cert5'],
            # ConstantesMaitreDesComptes.CHAMP_CLE: 'Une cle chiffree 5',
            ConstantesMaitreDesComptes.CHAMP_RESET_CERTIFICATS:
            False,
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_ASSOCIER_CERTIFICAT
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_ajouter_certificat_navigateur(self):
        transaction = {
            'nomUsager': '*****@*****.**',
            'idmg': 'abcd1234',
            'fingerprint': 'mon_fingerprint',
            'cleChiffree': 'clePriveeNavigateurChiffreePem',
            'certificat': 'certNavigateurPem',
            'motdepassePartiel': 'motdepassePartielServeurBuffer',
            'expiration': 12345678,
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM,
            ConstantesMaitreDesComptes.TRANSACTION_AJOUTER_NAVIGATEUR
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def transaction_maj_usager_totp(self):
        transaction = {
            "totp": {
                "chiffrement":
                "mgs1",
                "uuid-transaction":
                "ae3f9e1e-2cad-4838-ae01-c797b525abaa",
                "identificateurs_document": {
                    "libelle": "proprietaire",
                    "champ": "totp"
                },
                "secret_chiffre":
                "rEfqbgEjli3zxlWIjOeTxvAEY4RQVxR9PIIuCKgWA1T+Z1gQvaEBfP4Teu0hP6SYG0Exumxdtrl5f8VjB1TPnUOV6twOmGmqXQIPaxhlwNs="
            },
            'nomUsager': 'proprietaire',
        }
        domaine_action = '.'.join([
            ConstantesMaitreDesComptes.DOMAINE_NOM, 'MaitreDesComptes.' +
            ConstantesMaitreDesComptes.TRANSACTION_MAJ_USAGER_TOTP
        ])
        enveloppe = self.generateur.soumettre_transaction(
            transaction, domaine_action, 'abcd-1234', self.queue_name)
        print("Envoi : %s" % enveloppe)
        return enveloppe

    def executer(self):
        self.requete_info_proprietaire()
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(json.dumps(json.loads(body.decode('utf-8')), indent=4))
        print("Channel : " + str(ch))
        print("Method : " + str(method))
        print("Properties : " + str(properties))
        print("Channel virtual host : " +
              str(ch.connection.params.virtual_host))

    def commander_arreter_messagerie(self):
        requete = {
            "nom": "Messagerie",
            "module": "millegrilles.domaines.Messagerie",
            "classe": "GestionnaireMessagerie"
        }
        domaine_action = 'commande.domaines.' + ConstantesDomaines.COMMANDE_DOMAINE_ARRETER
        enveloppe_val = self.generateur.transmettre_commande(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def commander_demarrer_senseurspassifs(self):
        requete = {
            "nom": "SenseursPassifs",
            "module": "millegrilles.domaines.SenseursPassifs",
            "classe": "GestionnaireSenseursPassifs"
        }
        domaine_action = 'commande.domaines.' + ConstantesDomaines.COMMANDE_DOMAINE_DEMARRER
        enveloppe_val = self.generateur.transmettre_commande(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def commander_arreter_senseurspassifs(self):
        requete = {
            "nom": "SenseursPassifs",
            "module": "millegrilles.domaines.SenseursPassifs",
            "classe": "GestionnaireSenseursPassifs"
        }
        domaine_action = 'commande.domaines.' + ConstantesDomaines.COMMANDE_DOMAINE_ARRETER
        enveloppe_val = self.generateur.transmettre_commande(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def executer(self):
        # sample.commander_arreter_messagerie()
        # sample.commander_demarrer_senseurspassifs()
        sample.commander_arreter_senseurspassifs()
Example #30
0
class MessagesSample(BaseCallback):
    def __init__(self):
        super().__init__(contexte)
        self.contexte.message_dao.register_channel_listener(self)
        self.generateur = GenerateurTransaction(self.contexte)

        self.channel = None
        self.event_recu = Event()

    def on_channel_open(self, channel):
        # Enregistrer la reply-to queue
        self.channel = channel
        channel.queue_declare(durable=True,
                              exclusive=True,
                              callback=self.queue_open_local)

    def queue_open_local(self, queue):
        self.queue_name = queue.method.queue
        print("Queue: %s" % str(self.queue_name))

        self.channel.basic_consume(self.callbackAvecAck,
                                   queue=self.queue_name,
                                   no_ack=False)
        self.executer()

    def run_ioloop(self):
        self.contexte.message_dao.run_ioloop()

    def deconnecter(self):
        self.contexte.message_dao.deconnecter()

    def traiter_message(self, ch, method, properties, body):
        print("Message recu, correlationId: %s" % properties.correlation_id)
        print(json.dumps(json.loads(body.decode('utf-8')), indent=4))
        print("Channel : " + str(ch))
        print("Method : " + str(method))
        print("Properties : " + str(properties))
        print("Channel virtual host : " +
              str(ch.connection.params.virtual_host))

    def requete_liste_domaines(self):
        requete = {}
        domaine_action = ConstantesCatalogueApplications.REQUETE_LISTE_DOMAINES
        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def requete_liste_applications(self):
        requete = {}
        domaine_action = ConstantesCatalogueApplications.REQUETE_LISTE_APPLICATIONS
        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def requete_domaine(self):
        requete = {'nom': 'SenseursPassifs'}
        domaine_action = ConstantesCatalogueApplications.REQUETE_INFO_DOMAINE
        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def requete_application(self):
        requete = {'nom': 'blynk'}
        domaine_action = ConstantesCatalogueApplications.REQUETE_INFO_APPLICATION
        enveloppe_val = self.generateur.transmettre_requete(
            requete,
            domaine_action,
            reply_to=self.queue_name,
            correlation_id='efgh')
        print("Envoi metadata: %s" % enveloppe_val)

    def executer(self):
        # sample.requete_liste_domaines()
        sample.requete_liste_applications()