Exemplo n.º 1
0
 def create_db(self, context={}):
     data = context["data"]
     if data["super_password"] != config.get("super_password"):
         raise Exception("Invalid super admin password")
     db_name = data["db_name"]
     admin_password = data["admin_password"]
     use_demo = data.get("use_demo")
     if use_demo:
         base_sql = pkg_resources.resource_string("netforce_general", "data/base_demo.sql").decode()
     else:
         base_sql = pkg_resources.resource_string("netforce_general", "data/base.sql").decode()
     print("creating db...")
     db = database.connect("template1")
     db._db.set_isolation_level(0)
     db.execute("CREATE DATABASE %s" % db_name)
     db.close()
     print("initializing db...")
     db = database.connect(db_name)
     db.execute(base_sql)
     db.execute("UPDATE base_user SET name='Admin',login='admin',password=%s WHERE id=1", admin_password)
     db.commit()
     print("done!")
     return {
         "next": {
             "name": "manage_db"
         },
         "flash": "Database created successfully",
     }
Exemplo n.º 2
0
 def post(self):
     dbname=self.get_argument("dbname")
     uuid=self.get_argument("uuid")
     submit=self.get_argument("submit")
     db=database.connect(dbname)
     clear_cache()
     try:
         res=get_model("sale.quot").search([["uuid","=",uuid]])
         if not res:
             raise Exception("Invalid UUID")
         quot_id=res[0]
         quot=get_model("sale.quot").browse(quot_id)
         if submit=="accept":
             quot.write({"state":"won"})
         elif submit=="reject":
             quot.write({"state":"lost"})
         elif submit=="send":
             vals={"related_id":"sale.quot,%s"%quot_id,"body": self.get_argument("message"),"from_id":1}
             get_model("message").create(vals)
         self.redirect("/view_quot?dbname=%s&uuid=%s"%(dbname,uuid))
         db.commit()
     except Exception as e:
         db.rollback()
         import traceback
         traceback.print_exc()
Exemplo n.º 3
0
 def copy_db(self, context={}):
     data = context["data"]
     if data["super_password"] != config.get("super_password"):
         raise Exception("Invalid super admin password")
     dbname = data["dbname"]
     new_dbname = data["new_dbname"]
     print("copying db...")
     # database.close_connections(dbname);
     db = database.connect("template1")
     db._db.set_isolation_level(0)
     db.execute("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=%s", dbname)
     db.execute("CREATE DATABASE %s WITH TEMPLATE %s" % (new_dbname, dbname))
     db.close()
     print("copying files...")
     fdir1 = os.path.join("static", "db", dbname, "files")
     if os.path.exists(fdir1):
         fdir2 = os.path.join("static", "db", new_dbname, "files")
         if not os.path.exists(fdir2):
             os.makedirs(fdir2)
         for f in os.listdir(fdir1):
             f1 = os.path.join(fdir1, f)
             f2 = os.path.join(fdir2, f)
             shutil.copy(f1, f2)
     return {
         "next": {
             "name": "login"
         },
         "flash": "Database copied successfully",
     }
Exemplo n.º 4
0
def start():
    global _check_times
    print("Running jobs in process %s..."%os.getpid())
    dbname = config.get("database")
    schema = config.get("schema")
    if dbname:
        check_dbs = [dbname]
    else:
        dbnames = config.get("databases", "")
        check_dbs = [x.strip() for x in dbnames.split(",")]
    print("check_dbs", check_dbs)
    manager = Manager()
    t = datetime.now()
    _check_times = manager.dict({db: t for db in check_dbs})
    for dbname in check_dbs:
        print("resetting jobs of db '%s'"%dbname)
        db=database.connect(dbname,schema)
        res=db.execute("UPDATE cron_job SET state='waiting' WHERE state in ('running','error')")
        db.commit()
    job_pool = Pool(processes=int(config.get("job_processes")))
    while 1:
        try:
            # print("_check_time",_check_times)
            t0 = datetime.now()
            t0_s = t0.strftime("%Y-%m-%d %H:%M:%S")
            for dbname, next_t in _check_times.items():
                if next_t > t0:
                    continue
                _check_times[dbname] = t0 + timedelta(seconds=60)
                print("Checking for scheduled jobs in database %s..." % dbname)
                db = database.connect(dbname,schema)
                db.begin()
                res = db.query("SELECT * FROM cron_job WHERE state='waiting' ORDER BY date")
                db.commit()
                new_next_t = None
                for job in res:
                    if job.date <= t0_s:
                        job_pool.apply_async(run_job, [dbname, dict(job)])
                    else:
                        new_next_t = datetime.strptime(job.date, "%Y-%m-%d %H:%M:%S")
                        break
                if new_next_t and new_next_t < _check_times[dbname]:
                    _check_times[dbname] = new_next_t
        except Exception as e:
            import traceback; traceback.print_exc()
            print("WARNING: failed to check for jobs: %s"%e)
        time.sleep(1)
Exemplo n.º 5
0
 def delete_db(self, context={}):
     data = context["data"]
     if data["super_password"] != config.get("super_password"):
         raise Exception("Invalid super admin password")
     dbname = data["dbname"]
     print("deleting db...")
     db = database.connect("template1")
     db._db.set_isolation_level(0)
     db.execute("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=%s", dbname)
     db.execute("DROP DATABASE %s" % dbname)
     db.close()
     return {
         "next": {
             "name": "login"
         },
         "flash": "Database deleted successfully",
     }
Exemplo n.º 6
0
 def get(self):
     dbname=self.get_argument("dbname")
     uuid=self.get_argument("uuid")
     db=database.connect(dbname)
     clear_cache()
     try:
         res=get_model("sale.quot").search([["uuid","=",uuid]])
         if not res:
             raise Exception("Invalid UUID")
         quot_id=res[0]
         quot=get_model("sale.quot").browse(quot_id)
         comp=get_model("company").browse(1)
         data={
             "logo": comp.logo,
             "state": quot.state,
             "partner_name": quot.partner_id.name,
             "number": quot.number,
             "exp_date": quot.exp_date,
             "user_name": quot.user_id.name,
             "comments": [],
         }
         if quot.documents:
             doc=quot.documents[0]
             fname=doc.file
         else:
             fname=None
         data["file"]=fname
         for msg in quot.comments:
             vals={
                 "date": msg.date,
                 "body": msg.body,
             }
             data["comments"].append(vals)
         data["num_comments"]=len(data["comments"])
         tmpl=get_template("view_quot")
         html=tmpl.render(data)
         self.write(html)
         db.commit()
     except Exception as e:
         db.rollback()
         import traceback
         traceback.print_exc()