예제 #1
0
    def insert_objects(self, row_ndx, objects, parentIndex=QModelIndex()):
        """ Insert new objects in the model. We assume those objects
        will *need* to be saved in the database (unless deleted first)
        """

        if not objects or len(objects) == 0:
            return

        if row_ndx < 0:
            row_ndx = 0

        self.beginInsertRows(parentIndex, row_ndx, row_ndx + len(objects) - 1)

        for obj in objects:

            if obj in self._objects:
                mainlog.error(
                    "Trying to add the same object twice into object model.")

            self._created_objects.add(obj)

            # mainlog.debug("insert_objects: inserting object {} at row {}".format(obj, row_ndx))
            self._objects.insert(row_ndx, obj)
            row_ndx += 1

        self.endInsertRows()
예제 #2
0
    def update_name_and_description(self, document_id: int, name: str,
                                    description: str):

        if not name:
            raise ServerException(ServerErrors.file_name_cannot_be_empty)
            # file_name_cannot_be_empty
            # raise Exception("Name cannot be empty")

        mainlog.debug('Renaming doc:{} to:{} with description:{}'.format(
            document_id, name, description))
        try:
            self._rename_file_in_storage(document_id, name)
        except Exception as ex:
            mainlog.error("Could not rename document {}".format(document_id))
            mainlog.exception(ex)

        doc = session().query(Document).filter(
            Document.document_id == document_id).one()
        doc.description = description or ""
        doc.filename = name
        audit_trail_service.record("DOCUMENT_RENAMED",
                                   "",
                                   document_id,
                                   commit=False)
        session().commit()
예제 #3
0
    def delete_action(self):
        if self.current_item:
            o_id = getattr( self.current_item, self.key_field)

            if o_id >= 0: # For some reason I have o_id = 0 somewhere...

                # mainlog.debug("About to delete {}".format(o_id))

                try:
                    if self.delete_object(o_id):
                        self.current_item = None # Do this only if delete was successful !
                        self.in_save = True
                        self._refresh_list()

                        # The current filter might lead to a 0-length list
                        # or we might delete the only item of the list
                        # In that case, we clear the form.

                        if self.list_view.model().rowCount() > 0:
                            self.list_view.selectRow(0)
                        else:
                            self._populate_form(None)

                        self.in_save = False

                except Exception as e:
                    showErrorBox(_("There was an error while deleting"),str(e),e)
                    return

            else:
                mainlog.error("The current object has no id => I can't delete it")
        else:
            showWarningBox(_("You have selected nothing for delete."),None)
            return
예제 #4
0
파일: connection.py 프로젝트: wiz21b/koi
def check_db_connection(db_url):
    # I need DB url because I didn't find a way to get that information
    # from the session(), connection()...

    # Rage hard, maxi vinyl

    import subprocess
    import re

    if not db_url:
        return False

    mainlog.debug("check_db_connection: Trying to connect to the database")
    try:
        session().connection().execute(
            "SELECT count(*) from {}.employees".format(DATABASE_SCHEMA))
        mainlog.debug("check_db_connection: Executed query")
        session().commit()
        mainlog.debug("check_db_connection: commited")

        return True
    except Exception as ex:
        mainlog.error("Can't query the database !!! Is it connected ?")

        ret = str(ex)

        # mainlog.exception(ex)

        if type(db_url) == list:
            db_url = db_url[0]

        server_host = re.search("(@.*:)",
                                db_url).groups()[0].replace("@", "").replace(
                                    ":", "")

        try:
            mainlog.info("I'll try a ping at {}".format(server_host))
            r = subprocess.Popen("\\Windows\\System32\\ping -n 1 " +
                                 server_host,
                                 stdout=PIPE,
                                 shell=False).stdout.read()
            mainlog.info("Ping to {} result is : {}".format(server_host, r))

            ret += "<br/><br/>"
            if "Reply" in r:
                mainlog.info(
                    "Ping was successful, the DB server machine seems up")
                ret += _(
                    " A ping was successful (so host is up, database is down)")
            else:
                ret += _(" A ping was not successful (so host is down)")

            return ret
        except Exception as ex:
            #mainlog.error(str(ex,'ASCII','replace'))
            return _("Ping failed, the host is down.")
예제 #5
0
    def roles(self):
        if not self._roles:
            return set()
        else:
            ret = set()
            for r in self._roles.split(','):
                try:
                    ret.add(RoleType.from_str(r))
                except Exception as ex:
                    mainlog.error(u"Unrecognized role : {}, skipping.".format(r))

            return ret
예제 #6
0
def get_server_version(url_version):
    try:
        response = urlopen(url_version, timeout=5)
        html = response.read().decode('ascii')
        version = StrictVersion(html.strip())
        mainlog.debug("Version advertised by server : {}".format(str(version)))
        return version
    except Exception as e:
        mainlog.error("I was unable to get the version from server {}".format(
            url_version))
        mainlog.error(e)
        return None
예제 #7
0
    def clear_caches(self):
        self._turnover_computation_cache = dict()

        for attr_name in dir(self):
            if "chart" in attr_name:
                a = getattr(self, attr_name)

                # We assume the function is decorated and has the clear_cache
                # method !

                try:
                    a.clear_cache()
                except Exception as ex:
                    mainlog.error(
                        "Error while refreshing {}".format(attr_name))
                    mainlog.exception(ex)
예제 #8
0
    def selected_item(self):
        mainlog.debug("FindOrder.selected_item")
        ndx = self.search_results_view.currentIndex()
        if ndx.isValid():
            ndx = self.search_results_view.model().index( ndx.row(), 0)

            item = ndx.data(Qt.UserRole)
            item_type = ndx.data(Qt.UserRole+1)

            if item_type == 'order':
                mainlog.debug("FindOrder.selected_item order_id={}".format(item))
                return dao.order_dao.find_by_id(item)
            elif item_type == 'order_part':
                mainlog.debug("FindOrder.selected_item order_part_id={}".format(item))
                return dao.order_part_dao.find_by_id(item)
            else:
                mainlog.error("Unsupported item type {}".format(item_type))
        else:
            mainlog.error("Invalid index")
            return None
예제 #9
0
    def _make_time_line_title(self, task):
        timeline_title = ""
        if isinstance(task, TaskOnOperation):
            timeline_title = u"{}: {} {}".format(
                task.operation.production_file.order_part.human_identifier,
                task.operation.operation_model.description, task.description)
            if task.machine_id:
                timeline_title += _(", on {}").format(
                    machine_service.find_machine_by_id(
                        task.machine_id).fullname)

        elif isinstance(task, TaskOnOrder):
            timeline_title = u"{}: {} {}".format(
                task.order.label, task.operation_definition.description,
                task.description)
        elif isinstance(task, TaskOnNonBillable):
            timeline_title = task.operation_definition.description

        else:
            mainlog.error("Unrecognized task : {}".format(type(task)))
            return task.description

        return timeline_title
예제 #10
0
    def show_star_on_widget(self, w, show=True):
        mainlog.debug("show_star_on_widget {} {}".format(w, show))

        n = self.stack.indexOf(w)

        if n < 0:
            mainlog.error("The widget was not found")
            return

        b = self.buttons_layout.itemAt(n).widget()

        widget_star = None
        for s in self.stars:
            if s.enlightened == b and s.enabled:
                mainlog.debug("Found a star for the widget")
                widget_star = s

        if show == False and widget_star:
            mainlog.debug("Removing a star")
            self.stars.remove(widget_star)
            widget_star.hide()
            widget_star.setParent(None)
            del widget_star
            return

        elif show == True and widget_star:
            mainlog.debug("Reshow")
            widget_star.show()
            widget_star.enabled = True

        elif show == True and not widget_star:

            mainlog.debug("Show new star")
            star = Star(b)
            star.show()
            star.raise_()
            self.stars.append(star)
예제 #11
0
def upgrade_process(args):
    if platform.system() != 'Windows':
        mainlog.info(
            "The upgrade process won't work on something else than Windows... I skip that."
        )
        return

    this_version = configuration.this_version  # the one of this very code
    mainlog.debug("Client version is {}".format(this_version))

    if args.no_update:
        mainlog.info("Skipping update process because --no-update is set")

        # This is rather strange. If we are started by regular Windows ways
        # (double click, cmd,...) PySide finds its DLL fine.
        # But, if it is started through the upgrade process (via Popen), then
        # it doesn't because Windows can't expand junction points correctly
        # (according to what I saw, this is not a bug in windows, but rather a
        # feature to prevent old code to misuse junction points)
        # So, for this code to work, one has to make sure that _setupQtDir
        # is not called during the import but right after (else it crashes).

        # This is how to patch the __init__py of PySide :

        # def _setupQtDirectories(zedir=None):
        #     import sys
        #     import os
        #     from . import _utils
        #
        #     if zedir:
        #         pysideDir = zedir
        #     else:
        #         pysideDir = _utils.get_pyside_dir()
        #

        try:
            from PySide import _setupQtDirectories
        except Exception as ex:
            mainlog.error(
                "Unable to import _setupQtDirectories. Remember this was a bug fix, make sure "
                +
                "_setupQtDirectories is not called at the end of the __init__.py of pyside. "
                + "Check the comments in the code for more info.")
            mainlog.exception(ex)
            return

        if getattr(sys, 'frozen', False):
            # Frozen
            mainlog.debug("Fixing Qt import on frozen exe {}".format(
                os.path.normpath(os.getcwd())))
            _setupQtDirectories(os.path.normpath(os.getcwd()))
        else:
            mainlog.debug("Fixed Qt import on NON frozen exe")
            _setupQtDirectories()

        return

    next_version = get_server_version(
        configuration.update_url_version
    )  # available on the server (abd maybe already downloaded)
    current_version = find_highest_installed_version(
    )  # one we have downloaded in the past

    mainlog.info(
        "This version is {}, last downloaded version = {}, version available on server = {}"
        .format(this_version, current_version, next_version))

    if (not current_version or (current_version and this_version >= current_version)) and \
            (not next_version or (next_version and this_version >= next_version)):
        mainlog.info(
            "The available versions are not more recent than the current one. No update necessary."
        )
        return

    codename = configuration.get("Globals", "codename")

    # Update only if we have no current version or if the
    # next version is higher than ours

    if next_version and (not current_version
                         or next_version > current_version):

        try:
            tmpfile = make_temp_file(prefix='NewVersion_' +
                                     version_to_str(next_version),
                                     extension='.zip')
            download_file(configuration.update_url_file, tmpfile)

            newdir = os.path.join(
                get_data_dir(), "{}-{}".format(codename,
                                               version_to_str(next_version)))
            extractAll(tmpfile, newdir)

            # show that we actually downloaded something
            current_version = next_version
        except Exception as ex:
            mainlog.error(
                "The download of version {} failed. Therefore, I'll go on with the current one."
                .format(next_version))
            mainlog.exception(ex)

    # If we were able to download a version now or in the
    # past, then use this one. If not, then we run the
    # program (that is, the version that was installed
    # by the user)

    if current_version:
        current_dir = os.path.join(
            get_data_dir(), "{}-{}".format(codename,
                                           version_to_str(current_version)))

        # --no-update "signals" the control transfer (without it we'd
        # try to update with the latest version again creating an
        # endless loop)

        # os.chdir(os.path.join(current_dir,codename)) # FIXME Not sure this is useful; too tired to test
        cmd = [
            os.path.join(os.path.join(current_dir, codename),
                         codename + '.exe'), '--no-update'
        ]
        mainlog.info("Transferring control to {}".format(' '.join(cmd)))

        # DETACHED_PROCESS = 0x00000008
        # CREATE_NEW_PROCESS_GROUP = 0x00000200
        # subprocess.Popen( cmd,cwd=os.path.join(current_dir,'xxx'),creationflags=DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP)

        # From what I can see WinExec don't run in os.getcwd(), so I give it an absolute path.

        try:
            # win32api.WinExec will *NOT* block. The new version is run
            # in parallel. This allow us to quit so we don't have two
            # instances of Koi running simulatenaously

            # Unfortunaately, because of that it's hard to build a watch
            # dog that will protect us against a broken upgrade.
            # For example, we'd have to release our log files...

            res = win32api.WinExec(" ".join(cmd), win32con.SW_SHOWMAXIMIZED)
            sys.exit(RETURN_CODE_SUCCESS)

        except Exception as ex:
            mainlog.error(
                "Control transfer failed. There was an error while starting the newer version {}"
                .format(current_version))
            mainlog.exception(ex)
            return False