Beispiel #1
0
def get_docker_client(c_id):
    try:
        node = Node.get(Node.short_id == c_id)
        return node.host.get_docker_client()

    except peewee.DoesNotExist:
        return docker.from_env()
Beispiel #2
0
 def validate_node_name(self, field):
     node_name = unicode(self.node_name.data)
     node = Node.get(name=node_name)
     if not node:
         raise ValidationError('不存在此节点')
     self.node = node
     return node
Beispiel #3
0
 def post(self, urlname):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node = Node.get(urlname=urlname)
     if not node:
         return self.redirect_next_url()
     user = self.current_user
     args = self.request.arguments
     try:
         selected = args.get('parent_name')
         print(selected)
     except:
         selected = [n.name for n in node.parent_nodes]
         args = {'name': [node.name], 'urlname': [node.urlname],
                 'description': [node.description], 'style': [node.style]}
     form = NodeEditForm.init(Node.get_node_choices(), selected, args=args,
             node=node)
     if form.validate():
         node = form.save(user, node=node)
         result = {'status': 'success', 'message': '节点修改成功',
                 'node_url': node.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(node.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #4
0
 def validate_node_name(self, field):
     node_name = unicode(self.node_name.data)
     node = Node.get(name=node_name)
     if not node:
         raise ValidationError('不存在此节点')
     self.node = node
     return node
Beispiel #5
0
 def post(self, urlname):
     node = Node.get(urlname=urlname)
     if not node:
         return self.redirect_next_url()
     user = self.current_user
     kwargs = self.request.arguments
     try:
         selected = kwargs.get('parent_name')
         print(selected)
     except:
         selected = [n.name for n in node.parent_nodes]
         kwargs = {
             'name': [node.name],
             'urlname': [node.urlname],
             'description': [node.description],
             'style': [node.style]
         }
     form = NodeEditForm.init(Node.get_node_choices(),
                              selected,
                              node=node,
                              **kwargs)
     if form.validate():
         node = form.save(user, node=node)
         result = {
             'status': 'success',
             'message': '节点修改成功',
             'node_url': node.url
         }
         if self.is_ajax:
             return self.write(result)
         self.flash_message(**result)
         return self.redirect(node.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #6
0
async def show_container(c_id):
    lab = request.args.get('lab', 'DEMO')

    try:
        n = Node.get(Node.name == c_id)
        print('yeah, its a node name')
        return redirect(url_for('net_control.show_container', c_id=n.short_id, lab=lab))
    except peewee.DoesNotExist:
        print('yeah, its not a node name for sure')
        pass

    print('getting client')

    dc = get_docker_client(c_id)

    try:
        container = dc.containers.get(c_id)
    except docker.errors.NotFound:
        return abort(404)

    # processes = '; '.join([p[-1] for p in container.top(ps_args='-ww')['Processes']])
    processes = "FIXME"
    if processes:
        processes += ';'

    networks = '; '.join(container.attrs['NetworkSettings']['Networks'].keys())
    if networks:
        networks += ';'

    rules = get_container_rules(c_id)

    return await render_template('container_view.html', container=container,
                           processes=processes, networks=networks,
                           rules=rules, lab=lab)
Beispiel #7
0
 def get(self, urlname, category='all'):
     node = Node.get(urlname=urlname)
     if not node:
         raise tornado.web.HTTPError(404)
     page = force_int(self.get_argument('page', 1), 1)
     action = self.get_argument('action', None)
     tag = self.get_argument('tag', None)
     if tag:
         if tag == 'description':
             result = {'status': 'success', 'message': '简介传输成功',
                     'node_description': node.description,
                     'node_topic_count': node.topic_count,
                     'node_follow_count': node.follow_count}
             return self.write(result)
         if tag == 'relationship':
             parent_nodes = node.parent_nodes
             child_nodes = node.child_nodes
             sibling_nodes = node.sibling_nodes
             parent_json = []
             children_json = []
             sibling_json = []
             for p in parent_nodes:
                 parent_json.append(dict(id=p.id, name=p.name,
                     url=p.url,
                     description=p.description,
                     summary=p.summary,
                     urlname=p.urlname,
                     icon=p.icon))
             for c in child_nodes:
                 children_json.append(dict(id=c.id, name=c.name,
                     url=c.url,
                     description=c.description,
                     summary=c.summary,
                     urlname=c.urlname,
                     icon=c.icon))
             for s in sibling_nodes:
                 sibling_json.append(dict(id=s.id, name=s.name,
                     url=s.url,
                     description=s.description,
                     summary=s.summary,
                     urlname=s.urlname,
                     icon=s.icon))
             result = {'status': 'success', 'parent_nodes': parent_json, 'child_nodes':
                     children_json, 'sibling_nodes': sibling_json}
             return self.write(result)
     user = self.current_user
     if action and user:
         if action == 'follow':
             result = user.follow(node_id=node.id)
             if self.is_ajax:
                 return self.write(result)
             self.flash_message(result)
             return self.redirect_next_url()
     topic_count = count(node.get_topics(page=None, category=category))
     page_count = (topic_count + config.reply_paged - 1) // config.reply_paged
     url = node.url + '?category=' + category
     topics = node.get_topics(page=page, category=category)
     return self.render("node/index.html", node=node, topics=topics,
             category=category, page=page, page_count=page_count, url=url)
Beispiel #8
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "", ["install", "init",
            "iwanttodropdatabase"])
    except getopt.GetoptError:
        print("参数错误")
        sys.exit(2)

    for opt, val in opts:
        if opt == "--init":
            try:
                c.execute("create database %s" % config.db_name)
                c.execute("grant all privileges on %s.* to '%s'@'localhost' identified by '%s'" % (config.db_name, config.db_user, config.db_pass))
                c.execute("flush privileges")

                c.close()
                m.commit()
                m.close()
            except:
                pass
            db.generate_mapping(create_tables=True)
            if not Node.get(id=1):
                Node(name=u'根节点', urlname='root',
                        description=u'一切的根源').save()
            print("数据库表初始化成功")
        if opt == '--iwanttodropdatabase':
            key = raw_input("你确定要删除数据库?所有数据将消失,且无法恢复!!!(若确定请输入yes i do,否则直接按回车键!):\n")
            if key == "yes i do":
                key = raw_input("你确定要删除数据库?所有数据将消失,且无法恢复!!!(若确定请输入yes i do,否则直接按回车键!):\n")
            if key == "yes i do":
                key = raw_input("你确定要删除数据库?所有数据将消失,且无法恢复!!!(若确定请输入yes i do,否则直接按回车键!):\n")
            if key == "yes i do":
                try:
                    c.execute("drop database %s" % config.db_name)
                except Exception as e:
                    print(e)
                finally:
                    pass

                c.close()
                m.commit()
                m.close()
                print("已清空数据库!")
            else:
                print("已取消操作!")

        if opt == "--install":
            base_path = sys.path[0]
            try:
                print(requirements_path)
                os.system('sudo python %s/libs/pony/setup.py install' %
                        base_path)
                os.system('sudo pip install -r %s/requirements.txt' %
                        base_path)
            except e:
                print(e)
            finally:
                print("依赖安装成功")
Beispiel #9
0
 def get(self):
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #10
0
 def get(self):
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #11
0
 def post(self, node_id):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     category = self.get_argument('category', None)
     node = Node.get(id=node_id)
     if not node:
         return self.redirect_next_url()
     if self.request.files == {} or 'myimage' not in self.request.files:
         self.write({"status": "error", "message": "对不起,请选择图片"})
         return
     image_type_list = [
         'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/bmp',
         'image/x-png'
     ]
     icon_type_list = [
         'image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/bmp',
         'image/x-png', 'image/ico .ico', 'image/x-icon'
     ]
     send_file = self.request.files['myimage'][0]
     if category != 'icon' and send_file[
             'content_type'] not in image_type_list:
         self.write({
             "status":
             "error",
             "message":
             "对不起,仅支持 jpg, jpeg, bmp, gif, png\
                 格式的图片"
         })
         return
     if category == 'icon' and send_file[
             'content_type'] not in icon_type_list:
         self.write({
             "status":
             "error",
             "message":
             "对不起,仅支持 ico, jpg, jpeg, bmp, gif, png\
                 格式的图片"
         })
         return
     if len(send_file['body']) > 6 * 1024 * 1024:
         self.write({"status": "error", "message": "对不起,请上传6M以下的图片"})
         return
     tmp_file = tempfile.NamedTemporaryFile(delete=True)
     tmp_file.write(send_file['body'])
     tmp_file.seek(0)
     try:
         image_one = Image.open(tmp_file.name)
     except IOError, error:
         logging.info(error)
         logging.info('+' * 30 + '\n')
         logging.info(self.request.headers)
         tmp_file.close()
         self.write({"status": "error", "message": "对不起,此文件不是图片"})
         return
Beispiel #12
0
 def get(self):
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     if node:
         selected = node.name
     else:
         selected = None
     choices = Node.get_node_choices()
     form = TopicForm.init(choices=choices, selected=selected)
     return self.render("topic/create.html", form=form, node=node)
Beispiel #13
0
 def get(self):
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     if node:
         selected = node.name
     else:
         selected = None
     choices = Node.get_node_choices()
     form = TopicForm.init(choices=choices, selected=selected)
     return self.render("topic/create.html", form=form, node=node)
Beispiel #14
0
 def get(self, urlname):
     node = Node.get(urlname=urlname)
     if node:
         selected = [n.name for n in node.parent_nodes]
     else:
         return self.redirect_next_url()
     kwargs = {'name': [node.name], 'urlname': [node.urlname],
               'description': [node.description], 'style': [node.style]}
     form = NodeEditForm.init(Node.get_node_choices(), selected, node=node, **kwargs)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #15
0
async def tcdel():

    data = await request.json
    if data is None or 'id' not in data:
        return abort(400)

    c_id = data.get('id')

    dc = get_docker_client(c_id)
    try:
        container = dc.containers.get(c_id)
    except docker.errors.NotFound:
        return abort(404)

    cmd = 'tcdel --all --docker ' + c_id

    print('[ CMD ]', cmd, sep='\n', end='\n')

    try:
        node = Node.get(Node.short_id == c_id)

        if node.lab.runtime != 'cluster':
            raise peewee.DoesNotExist

        host = node.host
        dc = host.get_docker_client()
        lab_name = node.lab.name

        return_code, stdout = ssh_exec('tcwrap ' + cmd + ' --lab ' + lab_name, host.get_config())

        stderr = ''

    except peewee.DoesNotExist:
        dc = docker.from_env()

        tcset_process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE, universal_newlines=True,
                                       timeout=25)

        return_code = tcset_process.returncode
        stdout = tcset_process.stdout
        stderr = tcset_process.stderr


    print('[ returncode ] ', return_code)
    print('[ stdout ]', stdout, sep='\n')
    print('[ stderr ]', stderr, sep='\n')

    container = dc.containers.get(c_id)

    if is_router(container):
        routers_cache.delete(container.name)

    return 'OK', 200
Beispiel #16
0
def get_container_rules(c_id):
    try:
        node = Node.get(Node.short_id == c_id)

        if node.lab.runtime != "cluster":
            raise peewee.DoesNotExist

        return_code, stdout = ssh_exec('tcshow --docker {}'.format(c_id), node.host.get_config())

        stderr = ''

    except peewee.DoesNotExist:
        tcshow_process = subprocess.run(['tcshow', '--docker', c_id], stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE, universal_newlines=True)

        return_code = tcshow_process.returncode
        stdout = tcshow_process.stdout
        stderr = tcshow_process.stderr

    print('[ returncode ]', return_code, sep='\n', end='\n')
    print('[ stdout ]', stdout, sep='\n', end='\n')
    print('[ stderr ]', stderr, sep='\n', end='\n')

    data = json.loads(stdout[:stdout.rfind('}')+1])

    try:
        data = data.popitem()[1]['outgoing']['protocol=ip']
    except (KeyError, IndexError):
        data = {}
    print(data)

    ret = {}

    for k in ['loss', 'duplicate', 'corrupt', 'reorder']:
        if k in data and data[k] != "None":
            ret[k] = int(data[k][:-1])
        else:
            ret[k] = 0

    for k in ['delay', 'delay-distro']:
        if k in data and data[k] != "None":
            ret[k] = int(data[k].split('.')[0])
            # s will be last, so its ok
            ret[k + '_unit'] = next(filter(lambda i: i[0] in data[k], time_unit_map), [None, 'sec'])[1]
        else:
            ret[k] = 0
            ret[k + '_unit'] = 'msec'

    if "rate" in data and data['rate'] != "None":
        ret['rate'] = int(data["rate"][:-4])
        ret['rate_unit'] = data["rate"][-4:]

    return ret
Beispiel #17
0
 def get(self):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #18
0
 def get(self):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node_id = int(self.get_argument('node_id', 0))
     node = Node.get(id=node_id)
     if node:
         selected = [node.name]
     else:
         selected = []
     form = NodeForm.init(Node.get_node_choices(), selected)
     return self.render("node/create.html", form=form)
Beispiel #19
0
 def get(self, urlname):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node = Node.get(urlname=urlname)
     if node:
         selected = [n.name for n in node.parent_nodes]
     else:
         return self.redirect_next_url()
     args = {'name': [node.name], 'urlname': [node.urlname],
             'description': [node.description], 'style': [node.style]}
     form = NodeEditForm.init(Node.get_node_choices(), selected, args=args,
             node=node)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #20
0
def delete(request, key):
    form = ConfirmDeleteForm(request.form)
    if request.method == 'POST' and form.validate():
        if form.drop.data is True:
            node = Node.get(key)
            db.delete(node.blocks)
            Node.drop(key)
            return redirect('/admin/pages/', 301)
        if form.cascade.data is True:
            # cascade callback
            # inject a cascade callback that does
            #            # try to delete the key
            #            for i in range(2):
            #                if memcache.delete(node.get_absolute_url()) > 0:
            #                    break
            Node.drop(key, cascade=True)
            # FIXME: remove blocks from dropped Nodes
            return redirect(url_for('nut:pages/list_pages'), 301)

    node = Node.get(key)
    nodes = dict([(n.get_key(), n) for n in Node.all().filter("ancestors = ", key)])
    node = rec(node, nodes)
    return render_template('app:pages/confirm_delete.html', form=form,
                           node=node)
Beispiel #21
0
def edit(request, key):
    blocks = {}
    node = Node.get(key)
    add  = BlockAddForm(request.form, prefix='_add')
    if node.type == FOLDER:
        form = FolderForm(request.form, obj=node)
    else:
        form = PageForm(request.form, obj=node)
        form.layout.choices =  Layout.get_key_to_path()
        for block in node.blocks:
            blocks[block.name] = BlockForm(request.form, obj=block, prefix='__block:%s__' % block.name)

    if request.method == 'POST':
        blocks = dict(blocks)
        for key in request.form:
            if key.startswith('__block:'):
                name = key.split('__',2)[1][6:]
                if name not in blocks:
                    blocks[name] = BlockForm(request.form, prefix='__block:%s__' % name)
        if add.validate() and add.add.data is True:
            blocks[add.name.data] = BlockForm(prefix='__block:%s__' % add.name.data)
            add = BlockAddForm(prefix='_add')
        elif form.validate() and all([blocks[block].validate() for block in blocks]):
            layout_val = None
            if node.type == PAGE:
                layout_val = form.layout.data
                keys = blocks.keys()
                if form.layout.data == 'Layout:None':
                    form.layout.data = None
                else:
                    form.layout.data = Layout.get(form.layout.data.split(':',1)[1])
                for block in node.blocks:
                    blocks[block.name].auto_populate(block)
                    keys.remove(block.name)
                    block.put()
                for block in keys:
                    block = Block(node=node, name=block, body=blocks[block].body.data)
                    block.put()
            form.auto_populate(node)
            node.update()
            # invalidate cache
            node.invalidate_cache()

            if form.save.data is True:
                return redirect(url_for('nut:pages/list_pages'), 301)
            if layout_val is not None:
                form.layout.data = layout_val
    return render_template('app:pages/form.html', form=form, add=add, blocks=blocks.items(), mode='edit', node=node)
Beispiel #22
0
    def save(self, user, topic=None):
        data = self.data
        try:
            node_name = data.pop('node_name')
            if not self.node:
                self.node = Node.get(name=node_name)
        except KeyError:
            logging.info('no node_name in form data, data: %s', data)

        if not self.node:
            logging.info('node is None in form instance, self: %s', self)
        content = unicode(data.get('content'))
        data.update({'user_id': user.id, 'node_id': self.node.id,
                     'content': strip_xss_tags(content)})
        if topic:
            category = 'edit'
            pre_node_id = topic.node_id
            pre_title = topic.title
            pre_content = topic.content
            cur_node_id = data.get('node_id')
            cur_title = data.get('title')
            cur_content = data.get('content')
            changed = 0
            if pre_node_id != cur_node_id:
                topic.node.topic_count -= 1
                self.node.topic_count += 1
                diff_content = '主题节点从' + '<a class="node" href="' +\
                    topic.node.url + '">' + topic.node.name +\
                    '</a>移动到<a class="node" href="' + self.node.url + '">' +\
                    self.node.name + '</a>'
                changed = 1
            if pre_title != cur_title or pre_content != cur_content:
                content1 = '<p><h2>' + pre_title + '</h2></p>' + pre_content
                content2 = '<p><h2>' + cur_title + '</h2></p>' + cur_content
                diff_content = ghdiff.diff(content1, content2, css=None)
                changed = 1
            if changed == 1:
                topic.node_id = cur_node_id
                topic.title = cur_title
                topic.content = cur_content
                History(user_id=user.id, content=diff_content,
                        topic_id=topic.id).save()
            else:
                return topic
        else:
            category = 'create'
            topic = Topic(**data)
        return topic.save(category=category)
Beispiel #23
0
 def post(self):
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     user = self.current_user
     form = TopicForm(self.request.arguments)
     if form.validate():
         topic = form.save(user=user)
         topic.put_notifier()
         result = {'status': 'success', 'message': '主题创建成功',
                   'topic_url': topic.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(**result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("topic/create.html", form=form, node=node)
Beispiel #24
0
 def get(self, urlname):
     node = Node.get(urlname=urlname)
     if node:
         selected = [n.name for n in node.parent_nodes]
     else:
         return self.redirect_next_url()
     kwargs = {
         'name': [node.name],
         'urlname': [node.urlname],
         'description': [node.description],
         'style': [node.style]
     }
     form = NodeEditForm.init(Node.get_node_choices(),
                              selected,
                              node=node,
                              **kwargs)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #25
0
 def post(self, node_id):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     category = self.get_argument('category', None)
     node = Node.get(id=node_id)
     if not node:
         return self.redirect_next_url()
     if self.request.files == {} or 'myimage' not in self.request.files:
         self.write({"status": "error",
             "message": "对不起,请选择图片"})
         return
     image_type_list = ['image/gif', 'image/jpeg', 'image/pjpeg',
             'image/png', 'image/bmp', 'image/x-png']
     icon_type_list = ['image/gif', 'image/jpeg', 'image/pjpeg',
             'image/png', 'image/bmp', 'image/x-png', 'image/ico .ico',
             'image/x-icon']
     send_file = self.request.files['myimage'][0]
     if category != 'icon' and send_file['content_type'] not in image_type_list:
         self.write({"status": "error",
             "message": "对不起,仅支持 jpg, jpeg, bmp, gif, png\
                 格式的图片"})
         return
     if category == 'icon' and send_file['content_type'] not in icon_type_list:
         self.write({"status": "error",
             "message": "对不起,仅支持 ico, jpg, jpeg, bmp, gif, png\
                 格式的图片"})
         return
     if len(send_file['body']) > 6 * 1024 * 1024:
         self.write({"status": "error",
             "message": "对不起,请上传6M以下的图片"})
         return
     tmp_file = tempfile.NamedTemporaryFile(delete=True)
     tmp_file.write(send_file['body'])
     tmp_file.seek(0)
     try:
         image_one = Image.open(tmp_file.name)
     except IOError, error:
         logging.info(error)
         logging.info('+' * 30 + '\n')
         logging.info(self.request.headers)
         tmp_file.close()
         self.write({"status": "error",
             "message": "对不起,此文件不是图片"})
         return
Beispiel #26
0
 def save(self, user, role=None):
     data = self.data
     try:
         parent_name = data.pop('parent_name')
     except:
         parent_name = None
     data.update({'user_id': user.id})
     node = Node(**data).save()
     if not parent_name:
         if not NodeNode.get(parent_id=1, child_id=node.id):
             NodeNode(parent_id=1, child_id=node.id).save()
     else:
         for name in parent_name:
             parent = Node.get(name=name)
             if parent:
                 if not NodeNode.get(parent_id=parent.id, child_id=node.id):
                     NodeNode(parent_id=parent.id, child_id=node.id).save()
     return node
Beispiel #27
0
 def post(self):
     if not self.has_permission:
         return
     node_id = force_int(self.get_argument('node_id', 0), 0)
     node = Node.get(id=node_id)
     user = self.current_user
     form = TopicForm(self.request.arguments)
     if form.validate():
         topic = form.save(user=user)
         result = {'status': 'success', 'message': '主题创建成功',
                 'topic_url': topic.url}
         if self.is_ajax:
             return self.write(result)
         self.flash_message(result)
         return self.redirect(topic.url)
     if self.is_ajax:
         return self.write(form.result)
     return self.render("topic/create.html", form=form, node=node)
Beispiel #28
0
 def save(self, user, role=None):
     data = self.data
     try:
         parent_name = data.pop('parent_name')
     except:
         parent_name = None
     data.update({'user_id': user.id})
     node = Node(**data).save()
     if not parent_name:
         if not NodeNode.get(parent_id=1, child_id=node.id):
             NodeNode(parent_id=1, child_id=node.id).save()
     else:
         for name in parent_name:
             parent = Node.get(name=name)
             if parent:
                 if not NodeNode.get(parent_id=parent.id, child_id=node.id):
                     NodeNode(parent_id=parent.id, child_id=node.id).save()
     return node
Beispiel #29
0
 def get(self, urlname):
     if not self.has_permission:
         return
     if not self.current_user.is_admin:
         return self.redirect_next_url()
     node = Node.get(urlname=urlname)
     if node:
         selected = [n.name for n in node.parent_nodes]
     else:
         return self.redirect_next_url()
     args = {
         'name': [node.name],
         'urlname': [node.urlname],
         'description': [node.description],
         'style': [node.style]
     }
     form = NodeEditForm.init(Node.get_node_choices(),
                              selected,
                              args=args,
                              node=node)
     return self.render("node/edit.html", form=form, node=node)
Beispiel #30
0
    def save(self, user, role=None, node=None):
        data = self.data
        try:
            parent_name = data.pop('parent_name')
        except:
            parent_name = None
        data.update({'user_id': user.id})
        nns = NodeNode.select(lambda rv: rv.child_id == node.id)
        for nn in nns:
            nn.remove()
        if not parent_name:
            if not NodeNode.get(parent_id=1, child_id=node.id):
                NodeNode(parent_id=1, child_id=node.id).save()
        else:
            for name in parent_name:
                parent = Node.get(name=unicode(name))
                if parent:
                    if not NodeNode.get(parent_id=parent.id, child_id=node.id):
                        NodeNode(parent_id=parent.id, child_id=node.id).save()
        node = node.update(data)

        return node
Beispiel #31
0
    def save(self, user, role=None, node=None):
        data = self.data
        try:
            parent_name = data.pop('parent_name')
        except:
            parent_name = None
        data.update({'user_id': user.id})
        nns = NodeNode.select(lambda rv: rv.child_id == node.id)
        for nn in nns:
            nn.remove()
        if not parent_name:
            if not NodeNode.get(parent_id=1, child_id=node.id):
                NodeNode(parent_id=1, child_id=node.id).save()
        else:
            for name in parent_name:
                parent = Node.get(name=unicode(name))
                if parent:
                    if not NodeNode.get(parent_id=parent.id, child_id=node.id):
                        NodeNode(parent_id=parent.id, child_id=node.id).save()
        node = node.update(data)

        return node
Beispiel #32
0
 def get(self, urlname, category='all'):
     node = Node.get(urlname=urlname)
     if not node:
         raise tornado.web.HTTPError(404)
     page = force_int(self.get_argument('page', 1), 1)
     action = self.get_argument('action', None)
     tag = self.get_argument('tag', None)
     if tag:
         if tag == 'description':
             result = {
                 'status': 'success',
                 'message': '简介传输成功',
                 'node_description': node.description,
                 'node_topic_count': node.topic_count,
                 'node_follow_count': node.follow_count
             }
             return self.write(result)
         if tag == 'relationship':
             parent_nodes = node.parent_nodes
             child_nodes = node.child_nodes
             sibling_nodes = node.sibling_nodes
             parent_json = []
             children_json = []
             sibling_json = []
             for p in parent_nodes:
                 parent_json.append(
                     dict(id=p.id,
                          name=p.name,
                          url=p.url,
                          description=p.description,
                          summary=p.summary,
                          urlname=p.urlname,
                          icon=p.icon))
             for c in child_nodes:
                 children_json.append(
                     dict(id=c.id,
                          name=c.name,
                          url=c.url,
                          description=c.description,
                          summary=c.summary,
                          urlname=c.urlname,
                          icon=c.icon))
             for s in sibling_nodes:
                 sibling_json.append(
                     dict(id=s.id,
                          name=s.name,
                          url=s.url,
                          description=s.description,
                          summary=s.summary,
                          urlname=s.urlname,
                          icon=s.icon))
             result = {
                 'status': 'success',
                 'parent_nodes': parent_json,
                 'child_nodes': children_json,
                 'sibling_nodes': sibling_json
             }
             return self.write(result)
     user = self.current_user
     if action and user:
         if action == 'follow':
             result = user.follow(node_id=node.id)
             if self.is_ajax:
                 return self.write(result)
             self.flash_message(result)
             return self.redirect_next_url()
     topic_count = count(node.get_topics(page=None, category=category))
     page_count = (topic_count + config.reply_paged -
                   1) // config.reply_paged
     url = node.url + '?category=' + category
     topics = node.get_topics(page=page, category=category)
     return self.render("node/index.html",
                        node=node,
                        topics=topics,
                        category=category,
                        page=page,
                        page_count=page_count,
                        url=url)
Beispiel #33
0
def page_list(abs_path=''):
    base = Node.all().filter('abs_path = ', abs_path).get()
    if base:
        return Node.get(base.children)
    else:
        return None
Beispiel #34
0
 def validate_urlname(self, field):
     data = field.data.lower()
     node = Node.get(urlname=data)
     if node and node != self.node:
         raise ValidationError('此节点地址已存在')
Beispiel #35
0
 def validate_urlname(self, field):
     data = field.data.lower()
     if Node.get(urlname=data):
         raise ValidationError('此节点地址已存在')
Beispiel #36
0
 def validate_urlname(self, field):
     data = field.data.lower()
     if Node.get(urlname=data):
         raise ValidationError('此节点地址已存在')
Beispiel #37
0
async def tcset():
    data = await request.json

    c_id = request.args.get('id')
    if c_id is None:
        if data is None or 'id' not in data:
            return abort(400)
        c_id = data.get('id')
    else:
        data = await request.form

    try:
        data = to_int(data, ['rate', 'delay', 'loss',
                                     'corrupt', 'reorder', 'duplicate', 'delay-distro'])
    except ValueError:
        return "Error: wrong value, only integers are allowed", 400
    except TypeError:
        return "Error: invalid request body", 400

    # print(data)

    tcset_options = []
    delay_set = False

    # settings with units
    if 'rate' in data and data['rate'] > 0:
        if 'rate_unit' in data and data['rate_unit'] in ['Kbps', 'Mbps', 'Gbps']:
            rate_unit = data['rate_unit']
        else:
            rate_unit = 'Mbps'

        tcset_options.append('--rate ' + str(data['rate']) + rate_unit)

    if 'delay' in data and check_delay(data) and data['delay'] > 0:
        delay_set = True
        if 'delay_unit' in data and data['delay_unit'] in ['usec', 'msec', 'sec', 'min']:
            delay_unit = data['delay_unit']
        else:
            delay_unit = 'msec'
        tcset_options.append('--delay ' + str(data['delay']) + delay_unit)

    if 'delay-distro' in data and data['delay-distro'] > 0:
        
        if 'delay-distro_unit' in data and data['delay-distro_unit'] in ['usec', 'msec', 'sec', 'min']:
            delay_dist_unit = data['delay-distro_unit']
        else:
            delay_dist_unit = 'msec'

        if not delay_set:
            return "Error: delay distribution can only be set with the delay", 400
        tcset_options.append('--delay-distro ' + str(data['delay-distro']) + delay_dist_unit)

    # settings without units (percentage)
    if 'loss' in data and 0 <= data['loss'] <= 100:  # | ||
        tcset_options.append('--loss ' + str(data['loss']) + '%')  # | |_

    if 'corrupt' in data and 0 <= data['corrupt'] <= 100:
        tcset_options.append('--corrupt ' + str(data['corrupt']) + '%')

    if 'reorder' in data and 0 <= data['reorder'] <= 100:
        if not delay_set and data['reorder'] > 0:
            return "Error: reordering can only be set with the delay", 400
        tcset_options.append('--reordering ' + str(data['reorder']) + '%')

    if 'duplicate' in data and 0 <= data['duplicate'] <= 100:
        tcset_options.append('--duplicate ' + str(data['duplicate']) + '%')

    if not len(tcset_options):
        return 'Error: no settings were given', 400

    print('[ TCSET OPTIONS ]', tcset_options, sep='\n', end='\n')

    print('[ c_id ]', c_id, sep='\n', end='\n')

    if all([data[k] == 0 for k in ['loss', 'corrupt', 'reorder', 'duplicate', 'delay']]):
        cmd = 'tcdel --all --docker ' + c_id
    else:
        cmd = 'tcset --overwrite --docker {}  {}'.format(c_id, ' '.join(tcset_options))

    print('[ CMD ]', cmd, sep='\n', end='\n')

    try:
        node = Node.get(Node.short_id == c_id)

        if node.lab.runtime != 'cluster':
            raise peewee.DoesNotExist

        host = node.host
        dc = host.get_docker_client()
        lab_name = node.lab.name

        return_code, stdout = ssh_exec('tcwrap ' + cmd + ' --lab ' + lab_name, host.get_config())

        stderr = ''

    except peewee.DoesNotExist:
        dc = docker.from_env()

        tcset_process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE, universal_newlines=True,
                                       timeout=25)

        return_code = tcset_process.returncode
        stdout = tcset_process.stdout
        stderr = tcset_process.stderr

    print('[ returncode ] ', return_code)
    print('[ stdout ]', stdout, sep='\n')
    print('[ stderr ]', stderr, sep='\n')

    # return redirect(url_for('show_container', c_id=c_id))

    container = dc.containers.get(c_id)

    if cmd[:5] == 'tcdel':
        return 'OK', 200

    if return_code == 0:
        if is_router(container):
            routers_cache.set(container.name, True)

        return 'OK', 200
    else:
        return jsonify({
            'returncode': return_code,
            'stdout': stdout,
            'stderr': stderr
        }), 400
Beispiel #38
0
 def validate_urlname(self, field):
     data = field.data.lower()
     node = Node.get(urlname=data)
     if node and node != self.node:
         raise ValidationError('此节点地址已存在')
Beispiel #39
0
def init_node():
    from models import Node
    if not Node.get(id=1):
        Node(name=u'根节点', urlname='root',
                description=u'一切的根源').save()
Beispiel #40
0
    def post(self):
        path = urllib.unquote(self.request.path)
        m = parts.search(path)

        if m is None:
            self.error(404)
            return

        this_path = m.group(1)
        this_page = m.group(3) or 'index'
        this_ext = m.group(4) or 'html'

        # get section and node
        section = Section.all().filter('path =', this_path).get()
        node = Node.all().filter('section =', section).get()

        if section is None or node is None:
            self.error(404)
            return

        self.request.charset = 'utf8'

        # remove the horribleness from comment
        if this_page == 'comment' and this_ext == 'html':
            # firstly, check the 'faux' field and if something is in there, redirect
            faux = self.request.get('faux')
            if len(faux) > 0:
                logging.info('COMMENT: Spam comment detected (Faux field not empty)')
                self.redirect('/')
                return

            # comment submission for each section
            node = Node.get( self.request.get('node') )
            name = self.request.get('name')
            email = self.request.get('email')
            website = self.request.get('website')
            comment_text = re.sub('\r', '', self.request.get('comment'));

            # if there are more than 4 links (https?://) in the comment, we consider it spam
            if spammy_links(comment_text):
                logging.info('COMMENT: Spam comment detected (Too many links)')
                self.redirect('/')
                return

            # now create the comment
            comment = Comment(
                node = node,
                name = name,
                email = email,
                website = website,
                comment = comment_text,
                )
            comment.set_derivatives()
            comment.put()

            # send a mail to the admin
            admin_email = util.config_value('Admin Email')
            if mail.is_email_valid(admin_email):
                url_post = util.construct_url() + node.section.path + node.name + '.html'
                url_mod  = util.construct_url() + '/admin/comment/?key=' + str(comment.key()) + ';status='
                url_del  = util.construct_url() + '/admin/comment/del.html?key='+ str(comment.key())

                body = 'From: ' + name + ' <' + email + '>\n'
                body = body + 'Site: ' + website + '\n\n'
                body = body + comment_text + '\n\n'
                body = body + '*** Actions ***\n\n'
                body = body + 'ViewPost = ' + url_post + '\n\n'
                body = body + 'Approve  = ' + url_mod + 'approve\n'
                body = body + 'Reject   = ' + url_mod + 'reject\n'
                body = body + 'Delete   = ' + url_del + '\n'
                mail.send_mail(admin_email, admin_email, 'New comment on ' + section.path + node.name + '.html', body)
            else:
                # don't do anything
                logging.info('No valid email set, skipping sending admin an email for new comment')

            # redirect to the comment page
            self.redirect('comment.html?key=' + str(comment.key()))
            return

        elif this_page == 'message' and this_ext == 'html':
            # firstly, check the 'faux' field and if something is in there, redirect
            faux = self.request.get('faux')
            if len(faux) > 0:
                logging.info('MESSAGE: Spam detected, not saving')
                self.redirect('/')
                return

            # message submission for each section
            type = self.request.get('type')
            subject = self.request.get('subject')
            message = self.request.POST.items()
            redirect = self.request.get('redirect')

            # create the full URL we should be redirecting to
            full_redirect = util.construct_redirect( redirect )

            # now create the message
            msg = Message(
                type = type,
                subject = subject,
                message = message,
                )
            msg.put()

            # send a mail to the admin
            admin_email = util.config_value('Admin Email')
            if mail.is_email_valid(admin_email):
                body =        'type    : ' + type + '\n'
                body = body + 'subject : ' + subject + '\n'
                for k, v in self.request.POST.items():
                    body = body + k + ' : ' + v + '\n'
                mail.send_mail(admin_email, admin_email, '[' + type + '] ' + subject, body)
            else:
                # don't do anything
                logging.info('No valid email set, skipping sending admin an email for new message')

            self.redirect(full_redirect)
            return
        else:
            # not found
            self.error(404)
            return
Beispiel #41
0
def init_node():
    from models import Node
    if not Node.get(id=1):
        Node(name=u'根节点', urlname='root', description=u'一切的根源').save()