Git Product home page Git Product logo

devops's Introduction

devops's People

Contributors

heidsoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

devops's Issues

多云管理系统

  1. 工单管理:工单是运维工作的核心,需要对工单的创建、分配、处理和关闭等流程进行建模。每个工单会有一个状态(如新建、处理中、已关闭),相关联的用户(如创建者、处理者),以及一些附加信息(如工单描述、处理结果等)。

  2. 流程管理:流程管理涉及到工单处理的流程设计和执行。每个流程包含一系列的步骤,每个步骤可能需要特定的角色来执行,可能有特定的输入和输出,以及执行的条件和结果。

  3. 云服务管理:云服务管理涉及到云服务的创建、配置和管理。每个云服务可能有多种类型(如计算、存储、网络等),有自己的配置参数,以及与之关联的资源(如虚拟机、磁盘、IP地址等)。

  4. 配置管理数据库(CMDB):CMDB是存储IT资产信息的数据库,需要对IT资产的类型、属性、关系进行建模。每个IT资产可能与其他IT资产有关联(如服务器上运行的应用、应用使用的数据库等)。

  5. 系统监控:系统监控涉及到系统的健康状态、性能指标的收集和展示。每个监控项可能有一定的阈值,当实际值超过阈值时,会触发告警。

  6. 告警管理:告警管理涉及到告警的生成、分发和处理。每个告警有一个严重级别(如警告、严重、紧急),相关联的监控项,以及一些附加信息(如告警描述、处理建议等)。

  7. 云资源计费、预算管理和成本控制是运维系统的重要组成部分,可以按照以下方式进行领域建模:

  8. 云资源计费:云资源计费涉及到云资源的使用量和计费规则。每种云资源(如计算、存储、网络)都有自己的计费单位(如小时、GB、流量),以及与之关联的计费规则(如按量计费、包年包月)。

  9. 预算管理:预算管理涉及到预算的设定和执行。每个预算包含预算金额、预算期限、预算项目等信息,以及与之关联的实际支出。

  10. 成本控制:成本控制涉及到成本的计算、分析和优化。每个成本项包含成本金额、成本类型(如直接成本、间接成本)、成本来源等信息,以及与之关联的成本控制策略(如成本削减、成本转嫁)。

设计一个适合多种云服务提供商的表结构的关键在于找到所有这些云提供商共享的字段,并确定这些字段的数据类型。

以下是我设计的一个基本的表结构:

CREATE TABLE CloudInstances (
    id INT AUTO_INCREMENT,
    instance_id VARCHAR(255) NOT NULL,
    cloud_provider ENUM('AWS', 'Aliyun', 'Tencent') NOT NULL,
    instance_type VARCHAR(255),
    region VARCHAR(255),
    state ENUM('Running', 'Stopped', 'Terminated'),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

字段说明:

  • id:表的主键。
  • instance_id:云服务提供商提供的实例ID。
  • cloud_provider:云服务提供商的名称,这里使用了枚举类型来限制可能的值。
  • instance_type:实例的类型。
  • region:实例所在的地域。
  • state:实例的状态,这里使用了枚举类型来限制可能的值。
  • created_at:实例的创建时间。

这只是一个基本的表结构,你可能需要根据你的需求添加更多的字段,例如实例的IP地址,操作系统,CPU核数,内存大小等等。同时,你也可能需要创建更多的表来存储与实例相关的其他信息,例如实例的安全组,网络接口等等。

注意:这个表结构假设所有的instance_id在所有的云服务提供商之间都是唯一的。如果这个假设不成立,你可能需要将instance_idcloud_provider一起作为主键。

如果各个云的云主机字段不同,有以下几种方式可以考虑扩展表结构:

  1. 新增字段:直接在表中新增字段,字段名可以根据云服务提供商的名称和原始字段名进行组合,以便区分。
ALTER TABLE CloudInstances 
ADD COLUMN aws_field1 VARCHAR(255),
ADD COLUMN aliyun_field2 INT,
ADD COLUMN tencent_field3 TEXT;

这种方式适用于新增字段较少,且字段含义明确的情况。

  1. 创建新表:针对每个云服务提供商,创建一个新的表来存储特有的字段,然后通过instance_id将这些表与CloudInstances表进行关联。
CREATE TABLE AwsInstances (
    instance_id VARCHAR(255) NOT NULL,
    field1 VARCHAR(255),
    field2 INT,
    PRIMARY KEY (instance_id),
    FOREIGN KEY (instance_id) REFERENCES CloudInstances(instance_id)
);

这种方式适用于新增字段较多,或者各个云服务提供商的字段有较大差异的情况。

  1. 键值对:创建一个新的表来存储键值对,其中键是字段名,值是字段值。然后通过instance_id将这个表与CloudInstances表进行关联。
CREATE TABLE InstanceAttributes (
    id INT AUTO_INCREMENT,
    instance_id VARCHAR(255) NOT NULL,
    attribute_key VARCHAR(255) NOT NULL,
    attribute_value VARCHAR(255) NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (instance_id) REFERENCES CloudInstances(instance_id)
);

这种方式适用于新增字段非常多,或者字段的数量和名称经常变化的情况。

  1. JSON字段:在表中新增一个JSON类型的字段,用来存储各个云服务提供商特有的字段。
ALTER TABLE CloudInstances ADD COLUMN extra_attributes JSON;

这种方式适用于新增字段非常多,且字段的数量和名称经常变化的情况。但是需要注意的是,JSON字段的查询性能通常较差,而且不同的数据库系统对JSON字段的支持程度也不同。

设计多云管理系统的表结构时,需要考虑到数据的灵活性、查询效率、扩展性等因素。以下是一种可能的最佳实践:

  1. 资源表(resource_summary):存储所有云资源的公共属性,比如资源ID、资源名、资源提供商、资源类型等。
id resource_id resource_name provider type
1 ... ... 阿里云 ECS
2 ... ... AWS EC2
  1. 属性表(resource_attributes):存储每个资源的详细属性。这个表使用键值对的形式来存储数据,可以灵活地扩展新的属性。
id resource_id key value
1 1 cpu ...
2 1 memory ...
3 1 disk ...
4 2 os_type ...
  1. 集群表(cluster_summary):存储集群的信息。
id cluster_id cluster_name provider type
1 ... ... 阿里云 RDS
  1. 集群资源关系表(cluster_resource):存储集群和资源的关系。
id cluster_id resource_id
1 1 1
2 1 2

这样的设计既保证了数据的灵活性,又能较好地支持查询,同时也很容易扩展新的资源类型和属性。但需要注意的是,这种设计可能会导致查询变得复杂,因为需要联合查询多个表才能获取到完整的信息。

react

react 组件 return ( <> </>) 与 return
的区别

在React中,组件的返回值通常是使用return语句定义的。在这种情况下,return语句后面可以有两种不同的写法:

  1. return ... :这种写法使用了JSX语法,即将HTML标签写在JavaScript代码中。在这种写法中,``标签被用作最外层的容器,可以包含其他任何HTML元素。

  2. return (<>...):这种写法是使用了React的Fragment(片段)语法。Fragment允许在不引入额外的DOM元素的情况下返回多个子元素。使用<>和``标记来表示一个Fragment。

这两种写法在功能上是等效的,它们都会返回一个React元素。两者之间的主要区别在于语法上的不同。使用``的写法更接近传统的HTML语法,而使用<>...的写法则更简洁,并且避免了引入额外的DOM元素。

需要注意的是,使用<>...的写法需要确保项目中安装了React的版本16.2或更高版本,因为这个语法是在这个版本中引入的。如果使用的是较早的React版本,则只能使用``等HTML标签作为最外层容器。

nginx配置

 -----已开启新会话-----     

要配置TCP健康检查,您需要在nginx配置文件中添加相应的配置项。

首先,您需要使用stream模块来配置TCP代理。在nginx配置文件中,找到stream块,并在其中添加以下内容:

stream {
    server {
        listen 80;
        proxy_pass backend_servers;
        proxy_connect_timeout 3s;  # 设置连接超时时间
        proxy_timeout 10s;  # 设置代理超时时间
        health_check;  # 开启健康检查
    }
}

在上述配置中,listen指令指定了代理监听的端口号。proxy_pass指令指定了后端服务器的地址。proxy_connect_timeoutproxy_timeout分别设置了连接超时时间和代理超时时间。health_check指令开启了健康检查。

接下来,您需要为后端服务器配置健康检查。在nginx配置文件中,找到http块,并在其中添加以下
内容:

http {
    upstream backend_servers {
        server backend1.example.com:8080 max_fails=3 fail_timeout=30s;
        server backend2.example.com:8080 max_fails=3 fail_timeout=30s;
        check interval=5s rise=2 fall=3 timeout=2s type=tcp;
    }
}

在上述配置中,upstream指令定义了后端服务器的地址和端口号。max_fails指令设置了最大失败次数,fail_timeout指令设置了失败超时时间。check指令定义了健康检查的相关参数,包括检查间隔时间(interval)、成功次数(rise)、失败次数(fall)、超时时间(timeout)和检查类型(type)。

完成上述配置后,重新加载nginx配置文件即可生效。您可以使用nginx -t命令来检查配置文件是否正确,然后使用nginx -s reload命令来重新加载配置文件。

这样,nginx就会定期对后端服务器进行TCP健康检查,如果后端服务器不可用,nginx会自动将请求转发到其他可用的服务器。

 -----已开启新会话-----     

要配置 nginx 的 upstream http 健康检查,可以按照以下步骤进行操作:

  1. 在 nginx 的配置文件中,找到对应的 upstream 块,例如:
upstream backend {
    server backend1.example.com;
    server backend2.example.com;
}
  1. 在 upstream 块中添加 check 参数来启用健康检查,例如:
upstream backend {
    server backend1.example.com check;
    server backend2.example.com check;
}
  1. 配置健康检查的相关参数,例如:
upstream backend {
    server backend1.example.com check interval=3000 rise=2 fall=3;
    server backend2.example.com check interval=3000 rise=2 fall=3;
}

其中,interval 表示健康检查的间隔时间(毫秒),rise 表示在多少次连续健康检查成功后将服务器标记为健康,fall 表示在多少次连续健康检查失败后将服务器标记为不健康。

  1. 可以进一步配置其他的健康检查参数,例如:
upstream backend {
    server backend1.example.com check interval=3000 rise=2 fall=3 timeout=1000;
    server backend2.example.com check interval=3000 rise=2 fall=3 timeout=1000;
}

其中,timeout 表示每次健康检查的超时时间(毫秒)。

  1. 保存配置文件并重新加载 nginx 配置,例如使用命令 sudo service nginx reload

这样,nginx 就会按照配置的健康检查参数,定期检查 upstream 中的服务器的健康状况,并根据检查结果进行负载均衡。

统计docker生态系统相关项目

#!/bin/bash
#
########################
#author:heidsoft
#email:[email protected]
########################

git clone https://github.com/OnePaaS/libcontainer.git

git clone https://github.com/OnePaaS/docker-registry.git

git clone https://github.com/OnePaaS/libtrust.git

git clone https://github.com/OnePaaS/etcd.git

git clone https://github.com/OnePaaS/etcd-manager.git

git clone https://github.com/OnePaaS/dnsserver.git

git clone https://github.com/OnePaaS/docker-status.git

git clone https://github.com/OnePaaS/dockerlite.git

git clone https://github.com/OnePaaS/docker-network.git

git clone https://github.com/OnePaaS/libchan.git

git clone https://github.com/OnePaaS/docker-py.git

git clone https://github.com/OnePaaS/docker.git

git clone https://github.com/OnePaaS/distribution.git

git clone https://github.com/OnePaaS/swarm.git

git clone https://github.com/OnePaaS/fleet.git

git clone https://github.com/OnePaaS/rkt.git

git clone https://github.com/OnePaaS/coreos-overlay.git

git clone https://github.com/OnePaaS/flannel.git

git clone https://github.com/OnePaaS/go-namespaces.git

git clone https://github.com/OnePaaS/go-namespaces.git

git clone https://github.com/OnePaaS/linux.git

git clone https://github.com/OnePaaS/kubernetes.git

https://github.com/GoogleCloudPlatform

#docker  rpm下载包地址
https://get.docker.com/rpm/1.7.1/centos-6/RPMS/x86_64/docker-engine-1.7.1-1.el6.x86_64.rpm

vip 配置

keapalived
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/load_balancer_administration/ch-initial-setup-vsa
https://medium.com/@xmikex83/how-to-setup-an-highly-available-load-balancer-with-keepalived-and-haproxy-on-ubuntu-18-04-8bab7b77f715
https://support.huaweicloud.com/intl/en-us/usermanual-vpc/vpc_vip_0001.html
https://dataease.io/docs/installation/HA/keepalived_installation/

How to Configure Virtual IP Address (VIP) on CentOS
https://www.codeproject.com/Tips/1272324/How-to-Configure-Virtual-IP-Address-VIP-on-CentOS

ip addr show
Image 1

From the above output, we can see that the network interface is enp0s3.

Step 2
The configuration file for the enp0s3 network interface can be found in:
/etc/sysconfig/network-scripts.

In order to create a virtual network interface, we need to copy first the master configuration file.

cd /etc/sysconfig/network-scripts/
cp ifcfg-enp0s3 ifcfg-enp0s3:1
Step 3
Edit its content to set an appropriate network interface name and IP address - DEVICE, NAME, IPADDR in the virtual network configuration file.

/etc/sysconfig/network-scripts/cat ifcfg-enp0s3

TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="none"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="enp0s3"
UUID="b1d44459-6b90-435a-950e-9b6001cfcf1b"
DEVICE="enp0s3"
ONBOOT="yes"
IPADDR="192.168.40.222"
PREFIX="24"
GATEWAY="192.168.40.60"
DNS1="192.168.40.60"
IPV6_PRIVACY="no"
ZONE=public
/etc/sysconfig/network-scripts/ifcfg-enp0s3:1

TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="none"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="enp0s3"
UUID="b1d44459-6b90-435a-950e-9b6001cfcf1b"
DEVICE="enp0s3:1"
ONBOOT="yes"
IPADDR="192.168.40.224"
PREFIX="24"
GATEWAY="192.168.40.60"
DNS1="192.168.40.60"
IPV6_PRIVACY="no"
Step 4
Once you have edited the virtual network interface file, restart the network service.

systemctl restart network
Step 5
Check your network settings again and you’ll see the configured virtual network interface:

ip addr show

promethues

  • Counter(计数器):用于计量累加数量,可以使用折线图、堆积面积图、柱状图等图形进行展示。
  • Gauge(仪表盘):用于显示当前值,可以使用仪表盘、表格、单值等图形进行展示。
  • Histogram(直方图):用于展示样本数据的分布情况,可以使用直方图、箱形图等图形进行展示。
  • Summary(摘要):用于展示样本数据的分布情况和汇总信息,可以使用直方图、箱形图、折线图等图形进行展示。

dstat

dstat

dstat 是一个可以取代vmstat,iostat,netstat和ifstat这些命令的多功能产品。dstat克服了这些命令的局限并增加了一些另外的功能,增加了监控项,也变得更灵活了。dstat可以很方便监控系统运行状况并用于基准测试和排除故障。

dstat可以让你实时地看到所有系统资源,例如,你能够通过统计IDE控制器当前状态来比较磁盘利用率,或者直接通过网络带宽数值来比较磁盘的吞吐率(在相同的时间间隔内)。

dstat将以列表的形式为你提供选项信息并清晰地告诉你是在何种幅度和单位显示输出。这样更好地避免了信息混乱和误报。更重要的是,它可以让你更容易编写插件来收集你想要的数据信息,以从未有过的方式进行扩展。

Dstat的默认输出是专门为人们实时查看而设计的,不过你也可以将详细信息通过CSV输出到一个文件,并导入到Gnumeric或者Excel生成表格中。

特性
结合了vmstat,iostat,ifstat,netstat以及更多的信息
实时显示统计情况
在分析和排障时可以通过启用监控项并排序
模块化设计
使用python编写的,更方便扩展现有的工作任务
容易扩展和添加你的计数器(请为此做出贡献)
包含的许多扩展插件充分说明了增加新的监控项目是很方便的
可以分组统计块设备/网络设备,并给出总数
可以显示每台设备的当前状态
极准确的时间精度,即便是系统负荷较高也不会延迟显示
显示准确地单位和和限制转换误差范围
用不同的颜色显示不同的单位
显示中间结果延时小于1秒
支持输出CSV格式报表,并能导入到Gnumeric和Excel以生成图形
安装方法
Ubuntu/Mint和Debin系统:

本地软件库中有相关安装包,你可以用下面命令安装:

# sudo apt-get install dstat
RHEL/Centos和Fedora系统:

你可以在romforge软件库中添加有相关安装包,参照指导,使用如下命令很简单就能进行安装:

# yum install dstat
ArchLinux系统:

相关软件包在社区资源库中,你可以用这个命令来安装:

# pacman -S dstat
使用方法
dstat的基本用法就是输入dstat命令,输出如下:


这是默认输出显示的信息:

CPU状态:CPU的使用率。这项报告更有趣的部分是显示了用户,系统和空闲部分,这更好地分析了CPU当前的使用状况。如果你看到"wait"一栏中,CPU的状态是一个高使用率值,那说明系统存在一些其它问题。当CPU的状态处在"waits"时,那是因为它正在等待I/O设备(例如内存,磁盘或者网络)的响应而且还没有收到。

磁盘统计:磁盘的读写操作,这一栏显示磁盘的读、写总数。

网络统计:网络设备发送和接受的数据,这一栏显示的网络收、发数据总数。

分页统计:系统的分页活动。分页指的是一种内存管理技术用于查找系统场景,一个较大的分页表明系统正在使用大量的交换空间,或者说内存非常分散,大多数情况下你都希望看到page in(换入)和page out(换出)的值是0 0。

系统统计:这一项显示的是中断(int)和上下文切换(csw)。这项统计仅在有比较基线时才有意义。这一栏中较高的统计值通常表示大量的进程造成拥塞,需要对CPU进行关注。你的服务器一般情况下都会运行运行一些程序,所以这项总是显示一些数值。

默认情况下,dstat每秒都会刷新数据。如果想退出dstat,你可以按"CTRL-C"键。

需要注意的是报告的第一行,通常这里所有的统计都不显示数值的。

这是由于dstat会通过上一次的报告来给出一个总结,所以第一次运行时是没有平均值和总值的相关数据。

但是dstat可以通过传递2个参数运行来控制报告间隔和报告数量。例如,如果你想要dstat输出默认监控、报表输出的时间间隔为3秒钟,并且报表中输出10个结果,你可以运行如下命令:

dstat 3 10
在dstat命令中有很多参数可选,你可以通过man dstat命令查看,大多数常用的参数有这些:

-l :显示负载统计量
-m :显示内存使用率(包括used,buffer,cache,free值)
-r :显示I/O统计
-s :显示交换分区使用情况
-t :将当前时间显示在第一行
–fs :显示文件系统统计数据(包括文件总数量和inodes值)
–nocolor :不显示颜色(有时候有用)
–socket :显示网络统计数据
–tcp :显示常用的TCP统计
–udp :显示监听的UDP接口及其当前用量的一些动态数据
当然不止这些用法,dstat附带了一些插件很大程度地扩展了它的功能。你可以通过查看/usr/share/dstat目录来查看它们的一些使用方法,常用的有这些:

-–disk-util :显示某一时间磁盘的忙碌状况
-–freespace :显示当前磁盘空间使用率
-–proc-count :显示正在运行的程序数量
-–top-bio :指出块I/O最大的进程
-–top-cpu :图形化显示CPU占用最大的进程
-–top-io :显示正常I/O最大的进程
-–top-mem :显示占用最多内存的进程
举一些例子:

查看全部内存都有谁在占用:

dstat -g -l -m -s --top-mem
显示一些关于CPU资源损耗的数据:

dstat -c -y -l --proc-count --top-cpu
如何输出一个csv文件
想输出一个csv格式的文件用于以后,可以通过下面的命令:

# dstat –output /tmp/sampleoutput.csv -cdn
via: http://linuxaria.com/howto/linux-terminal-dstat-monitoring-tools

红帽操作系统培训

红帽8操作系统

dnf --> yum (yum是dnf软连接)
yum module

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/installing_managing_and_removing_user-space_components/introduction-to-modules_using-appstream
https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_linux/8/html/installing_managing_and_removing_user-space_components/index

调优

https://access.redhat.com/documentation/zh-cn/red_hat_enterprise_linux/8/html/monitoring_and_managing_system_status_and_performance/tuned-profiles-distributed-with-rhel_getting-started-with-tuned

启动过程

  • multi-user.target
  • systemctl list-dependences

ansible

sudoer 配置

[root@localhost ~]# cd /etc/sudoers.d/
[root@localhost sudoers.d]# ls -alh
total 12K
drwxr-x---.  2 root root    6 Oct 30  2018 .
drwxr-xr-x. 85 root root 8.0K Aug 20 23:03 ..
[root@localhost sudoers.d]# pwd
/etc/sudoers.d
[root@localhost sudoers.d]#

[root@localhost sudoers.d]# touch student
[root@localhost sudoers.d]# chmod 400 student
[root@localhost sudoers.d]# pwd
/etc/sudoers.d
[root@localhost sudoers.d]#


在Linux中,文件权限由三组权限组成:所有者权限、群组权限和其他用户权限。每个权限组又包含读(r)、写(w)和执行(x)三个权限。

数字形式的权限表示方法是将每个权限用数字表示,r为4,w为2,x为1。然后将对应权限的数字相加即可得到该权限组的数字形式。

对于权限组400,它表示只有所有者拥有读权限,没有写权限和执行权限。其他用户和群组用户没有任何权限,即只有所有者可以读取该文件,其他用户无法访问。

linux motd

Linux中的motd(Message of the Day)是一个文本文件,用于在用户登录系统时显示一条消息。motd文件通常位于/etc目录下,文件名为motd。

motd的作用和用途有以下几个方面:

1. 提供系统信息:motd可以用来显示系统的一些基本信息,如主机名、操作系统版本、内核版本等。这对于管理员来说是很有用的,可以快速了解系统的基本情况。

2. 提示系统状态:motd还可以用来显示系统的状态,如CPU负载、内存使用情况、磁盘空间等。这对于管理员来说是很有用的,可以及时发现系统的负载情况,以便进行调整和优化。

3. 发布公告:motd可以用来发布系统相关的公告,如计划维护时间、重要更新通知等。这对于用户来说是很有用的,可以及时了解系统维护和更新的情况。

4. 自定义消息:motd还可以用来显示自定义的消息,如欢迎信息、警告信息等。这对于管理员来说是很有用的,可以向用户发送特定的消息。

总的来说,motd在Linux系统中起到了提供系统信息、提示系统状态、发布公告和显示自定义消息的作用,使得用户和管理员能够更好地了解和管理系统。

sudo su 用法

https://sysin.org/blog/linux-root/#:~:text=Wheel%20%E7%BB%84%E6%98%AFUnix%20%E7%B3%BB%E7%BB%9F,root%20%E8%BA%AB%E4%B8%8A%E4%BB%BB%E4%BD%95%E7%9A%84%E7%89%B9%E6%9D%83%E3%80%82

jvm

本地内存分析

https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr007.html
https://tech.meituan.com/2018/10/18/netty-direct-memory-screening.html?from=timeline&isappinstalled=0

Total:  reserved=664192KB,  committed=253120KB                                           <--- total memory tracked by Native Memory Tracking
 
-                 Java Heap (reserved=516096KB, committed=204800KB)                      <--- Java Heap
                            (mmap: reserved=516096KB, committed=204800KB)
 
-                     Class (reserved=6568KB, committed=4140KB)                          <--- class metadata
                            (classes #665)                                               <--- number of loaded classes
                            (malloc=424KB, #1000)                                        <--- malloc'd memory, #number of malloc
                            (mmap: reserved=6144KB, committed=3716KB)
 
-                    Thread (reserved=6868KB, committed=6868KB)
                            (thread #15)                                                 <--- number of threads
                            (stack: reserved=6780KB, committed=6780KB)                   <--- memory used by thread stacks
                            (malloc=27KB, #66)
                            (arena=61KB, #30)                                            <--- resource and handle areas
 
-                      Code (reserved=102414KB, committed=6314KB)
                            (malloc=2574KB, #74316)
                            (mmap: reserved=99840KB, committed=3740KB)
 
-                        GC (reserved=26154KB, committed=24938KB)
                            (malloc=486KB, #110)
                            (mmap: reserved=25668KB, committed=24452KB)
 
-                  Compiler (reserved=106KB, committed=106KB)
                            (malloc=7KB, #90)
                            (arena=99KB, #3)
 
-                  Internal (reserved=586KB, committed=554KB)
                            (malloc=554KB, #1677)
                            (mmap: reserved=32KB, committed=0KB)
 
-                    Symbol (reserved=906KB, committed=906KB)
                            (malloc=514KB, #2736)
                            (arena=392KB, #1)
 
-           Memory Tracking (reserved=3184KB, committed=3184KB)
                            (malloc=3184KB, #300)
 
-        Pooled Free Chunks (reserved=1276KB, committed=1276KB)
                            (malloc=1276KB)
 
-                   Unknown (reserved=33KB, committed=33KB)
                            (arena=33KB, #1)


这些数据提供了与内存使用情况相关的详细信息。下面是对每个数据字段的含义解释:

- Java Heap (Java堆): 这是Java虚拟机分配给Java应用程序的内存空间。它包括已保留的内存空间(reserved)和已使用的内存空间(committed)。

- Class (类): 这是用于存储Java类元数据的内存空间。它包括已保留的内存空间和已使用的内存空间。还提供了有关已加载类数量和通过malloc分配的内存大小的信息。

- Thread (线程): 这是用于存储线程相关数据的内存空间。它包括已保留的内存空间和已使用的内存空间。还提供了有关线程数量、线程堆栈内存使用情况、通过malloc分配的内存大小以及资源和句柄区域内存大小的信息。

- Code (代码): 这是用于存储Java应用程序的字节码和本地代码的内存空间。它包括通过malloc分配的内存大小和通过mmap分配的内存大小。

- GC (垃圾回收): 这是用于存储垃圾回收相关数据的内存空间。它包括通过malloc分配的内存大小和通过mmap分配的内存大小。

- Compiler (编译器): 这是用于存储编译

器相关数据的内存空间。它包括通过malloc分配的内存大小和通过arena分配的内存大小。

- Internal (内部): 这是用于存储内部数据结构和状态的内存空间。它包括通过malloc分配的内存大小和通过mmap分配的内存大小。

- Symbol (符号): 这是用于存储Java符号(如类名、方法名等)的内存空间。它包括通过malloc分配的内存大小和通过arena分配的内存大小。

- Memory Tracking (内存跟踪): 这是用于跟踪内存使用情况的内存空间。它包括通过malloc分配的内存大小。

- Pooled Free Chunks (空闲块池): 这是用于存储空闲内存块的内存空间。它包括通过malloc分配的内存大小。

- Unknown (未知): 这是无法归类到其他内存空间类型的内存空间。它包括通过arena分配的内存大小。

总体而言,这些数据提供了不同类型内存空间的使用情况,帮助我们了解Java应用程序的内存消耗情况以及各个内存区域的分配情况。



JVM堆外内存主要由以下部分组成:

1. 直接内存(Direct Memory):直接内存是一种堆外内存,它是通过使用Java NIO(New Input/Output)库来分配的。直接内存是由操作系统直接分配和管理的,不受JVM堆大小的限制。它可以通过ByteBuffer类来访问和操作。

2. 本地方法栈(Native Method Stack):本地方法栈也是一种堆外内存,用于存储Java程序中调用本地方法(Native Method)时的数据和状态。本地方法栈是线程私有的,每个线程都有自己的本地方法栈。

3. 线程栈(Thread Stack):线程栈也是一种堆外内存,用于存储线程执行方法时的数据和状态。线程栈是线程私有的,每个线程都有自己的线程栈。

4. 程序计数器(Program Counter):程序计数器也是一种堆外内存,用于存储当前线程执行的字节码指令地址。程序计数器是线程私有的,每个线程都有自己的程序计数器。

这些部分组成了JVM堆外内存,它们在JVM的运行过程中发挥重要的作用。

工单系统与工作流

工单系统和工作流之间存在着紧密的关系。工单系统是指用于管理和跟踪工单的软件系统,它能够帮助组织有效地分配、处理和解决工单。而工作流则是指一系列的业务流程和规则,用于指导和控制工单的处理流程。

工单系统可以通过工作流的定义和配置,实现对工单的自动化处理和流转。具体来说,工单系统可以根据工作流的设定,自动将工单分配给相应的负责人或团队,根据工作流的规则和条件,自动触发不同的处理流程,以及根据工作流的状态和进度,自动发送通知和提醒。

通过工单系统与工作流的结合,可以提高工单处理的效率和准确性。工单系统可以帮助组织实现工单的自动化分配和处理,减少人工干预和错误,提高工单处理的速度和质量。同时,工作流可以帮助组织规范和统一工单处理的流程,确保每个工单都按照既定的规则和流程进行处理,提高工单处理的一致性和可追溯性。

总之,工单系统和工作流之间的关系是相辅相成的,通过它们的结合和配合,可以实现对工单处理的自动化和规范化,提高组织的工作效率和服务质量。

django深入

aliyun logstore-查询使用

`select time - time % 600 as time, 这个是什么意思

这是一段在阿里云Logstore中进行日志查询的SQL语句,主要的功能是对日志中的数据进行时间序列的回归预测。

  1. select __time__ - __time__ % 600 as time, count(1) as value from log group by time order by time limit 14400:从日志中选取时间和对应的值,并对时间进行处理(将其缩小到分钟级别),按照时间进行分组,然后按照时间进行排序,最后限制获取的数据条数为14400。
    1. 时间序列分析:通过这种方式,我们可以看到每10分钟的日志数量,这样可以帮助我们找出系统在什么时间段内的日志数量最多,有助于找出可能的系统问题或者峰值负载时间。
  1. ts_regression_predict(time, value, 144, 'origin', 1, 'avg') as res:使用时间序列回归预测函数对上一步获取的数据进行预测,预测的参数包括时间、值、历史数据的数量(144)、数据的类型('origin')、预测的步长(1)和预测值的计算方式('avg'),并将预测的结果保存为res。

  2. unnest(res) as t(key):将预测的结果进行展开,并将展开的结果保存为t(key)。

  3. select date_trunc('minute', cast(key[1] as bigint)) as "时间", key[2] as "真实值", key[3] as "预测值":从展开的结果中选取需要的字段,包括时间、真实值和预测值,并对时间进行处理(将其转换为分钟级别)。

按主机汇总PV

(host:*)| select host as Host, count(1) as PV group by host order by PV desc limit 10

日志按时间汇总

(*)| select __time__ - __time__ % 600 as time, count(1) as value from log group by time order by time #46

* | SELECT date_format(date_trunc('hour', __time__), '%m-%d %H:%i') as time, count(*) as count GROUP BY time ORDER BY time limit 1000

架构深入

sonarqube使用

java分析

# Here maven uses the default version of Java on the system but we specify that we want to analyze a Java 8 project.
mvn clean verify sonar:sonar \
  # other analysis parameters
  -Dsonar.java.jdkHome=/usr/lib/jvm/java-8-openjdk/
  # other analysis parameters

mvn -Dsonar.coverage.jacoco.xmlReportPaths=
      ../app-it/target/site/jacoco-aggregate/jacoco.xml
    sonar:sonar -Pcoverage

maven扫描集成

java内存溢出

ls 命令

ls -l --time-style=full-iso

ls -l --time-style=long-iso

ls -l --time-style=iso

ls -l --time-style=locale

ls -l --time-style=+%H:%M:%S:%D

ls --full-time

ls –-format=across

ls --format=comma

ls --format=horizontal

ls --format=long

ls --format=single-column

ls --format=verbose

ls --format=vertical

java BlockingQueue 队列

Disruptor队列是一种高性能的无锁队列,它采用了环形缓冲区的数据结构,能够实现高效的数据传输和异步处理。相比之下,BlockingQueue是Java标准库中的一个阻塞队列实现,它使用锁和条件变量来实现线程的同步和阻塞。

Disruptor队列的性能远胜于BlockingQueue的主要原因有以下几点:

  1. 无锁设计:Disruptor队列采用了无锁的设计,避免了锁带来的线程竞争和上下文切换的开销。相比之下,BlockingQueue使用锁和条件变量来实现线程的同步和阻塞,会导致线程竞争和上下文切换的开销增加。

  2. 高效的数据传输:Disruptor队列使用环形缓冲区的数据结构,能够实现高效的数据传输。生产者和消费者之间可以直接通过指针来传递数据,而不需要进行复制操作。相比之下,BlockingQueue需要进行数据的复制操作,增加了额外的开销。

  3. 异步处理:Disruptor队列支持异步处理模式,可以在多个线程之间进行数据传输和处理。生产者和消费者之间可以并行地进行数据传输和处理,从而提高了系统的并发性能。相比之下,BlockingQueue只能在一个线程中进行
    数据传输和处理,无法实现真正的并行处理。

综上所述,Disruptor队列的性能远胜于BlockingQueue。它适用于需要高性能和高并发处理的场景,如金融交易系统、网络服务器等。但是,由于Disruptor队列的实现相对复杂,使用起来也比较困难,因此在一些简单的场景下,还是可以使用BlockingQueue来实现线程的同步和阻塞。

BlockingQueue是Java标准库中的一个接口,它继承自Queue接口,用于实现生产者-消费者模型中的阻塞队列。它提供了一种线程安全的队列,可以在多线程环境下进行安全的数据交换。

BlockingQueue的原理是使用锁和条件变量来实现线程的同步和阻塞。它的主要目的是在队列为空时,消费者线程会被阻塞,直到有数据被生产者线程放入队列;在队列满时,生产者线程会被阻塞,直到有空间被消费者线程取出。

具体来说,BlockingQueue使用两个锁和两个条件变量来实现阻塞。一个锁用于保护队列的读写操作,另一个锁用于保护队列的长度和空间的计算。当队列为空时,消费者线程调用take方法时会被阻塞,直到有数据被放入队列,并通过条件变量唤醒消费者线程。当队列满时,生产者线程调用put方法时会被阻塞,直到有空间被释放,并通过条件变量唤醒生产者线程。

在实现中,BlockingQueue通常使用一个基于数组或链表的数据结构来存储数据,并提供了put、take、offer、poll等方法来实现数据的生产和消费。这些方法在插入或删除元素时会进行加锁,并通过条件变量来控制线程的阻塞和唤醒。

总的来说,BlockingQueue是Java标准库中用于实现线程安全的阻塞队列的接口。它通过锁和条件变量来实现线程的同步和阻塞,保证了多线程环境下的数据安全和顺序性。

BlockingQueue队列可以应用于以下场景:

  1. 多线程协作:BlockingQueue可以用于实现多线程之间的协作和数据传递。一个线程可以将数据放入队列,另一个线程可以从队列中取出数据进行处理,实现线程之间的数据传递和同步。
  2. 任务调度:BlockingQueue可以用于实现任务调度器,将需要执行的任务放入队列中,由另一个线程按照一定的策略取出任务进行执行。
  3. 限流和流量控制:BlockingQueue可以用于限制系统的并发处理能力,通过设置队列的容量,当队列满时,生产者线程将被阻塞,从而控制系统的并发度和资源消耗。

以下是一些编写代码的最佳实践:

  1. 选择合适的BlockingQueue实现:Java提供了多种BlockingQueue实现,如ArrayBlockingQueue、LinkedBlockingQueue等,选择适合你场景需求的实现。
  2. 使用合适的容量:根据实际情况设置队列的容量,避免过大或过小的容量对系统性能造成影响。可以根据系统的负载和资源限制来选择合适的容量。
  3. 错误处理和异常处理:在使用BlockingQueue时,需要注意处理可能出现的异常情况,如队列满或队列空时的阻塞和超时等。可以使用try-catch块来捕获异常,并根据具体情况进行错误处理。
  4. 控制并发度和线程安全:BlockingQueue是线程安全的,可以在多个线程之间安全地共享。但需要注意控制并发度,避免过多的线程同时操作队列,造成性能问题或竞态条件。
  5. 选择合适的阻塞操作:BlockingQueue提供了多种阻塞操作,如put()、take()、offer()、poll()等,根据具体需求选择合适的操作。需要注意选择合适的超时时间,避免线程长时间阻塞。
  6. 清理资源:在不需要使用BlockingQueue时,需要及时清理资源,调用close()或shutdown()方法来关闭队列,释放相关资源。
  7. 测试和调试:对使用BlockingQueue的代码进行充分的测试和调试,确保其正常工作和稳定性。可以使用单元测试和模拟数据来验证代码的正确性和性能。

以下是一个使用BlockingQueue实现任务调度器的示例:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class TaskScheduler {
    private BlockingQueue<Runnable> taskQueue;
    private Thread workerThread;

    public TaskScheduler() {
        taskQueue = new LinkedBlockingQueue<>();
        workerThread = new Thread(new Worker());
        workerThread.start();
    }

    public void scheduleTask(Runnable task) {
        taskQueue.offer(task); // 将任务放入队列}

    public void shutdown() {
        workerThread.interrupt(); // 中断工作线程
    }

    private class Worker implements Runnable {
        @Override
        public void run() {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    Runnable task = taskQueue.take(); // 从队列中取出任务
                    task.run(); // 执行任务
                }
            } catch (InterruptedException e) {
                // 线程被中断,结束任务调度
            }
        }
    }
}

使用示例:

public class Main {
    public static void main(String[] args) {
        TaskScheduler scheduler = new TaskScheduler();

        // 创建并添加任务
        Runnable task1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Task 1 executed");
            }
        };
        scheduler.scheduleTask(task1);

        Runnable task2 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Task 2 executed");
            }
        };
        scheduler.scheduleTask(task2);

        // 等待一段时间后关闭任务调度器
        try {
            Thread.sleep(5000);
            scheduler.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,我们创建了一个TaskScheduler类,它包含一个BlockingQueue作为任务队列,并有一个Worker内部类作为工作线程。在TaskScheduler的构造函数中,我们启动了工作线程。然后通过scheduleTask方法将任务放入队列中。工作线程不断从队列中取出任务并执行,直到被中断。在示例的主函数中,我们创建了两个任务,并将它们添加到任务调度器中。然后等待一段时间后,调用shutdown方法关闭任务调度器。
这样,任务调度器就可以将需要执行的任务放入队列中,并由另一个线程按照一定的策略取出任务进行执行。

以下是一个使用BlockingQueue进行系统并发处理能力限流的Java代码示例:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class OrderProcessor {
    private BlockingQueue<Order> orderQueue; // 订单队列
    private int maxConcurrency; // 最大并发处理能力

    public OrderProcessor(int maxConcurrency) {
        this.maxConcurrency = maxConcurrency;
        orderQueue = new LinkedBlockingQueue<>(maxConcurrency);
    }

    public void submitOrder(Order order) throws InterruptedException {
        orderQueue.put(order); // 将订单放入队列,如果队列已满则会阻塞
    }

    public void startProcessing() {
        for (int i = 0; i < maxConcurrency; i++) {
            Thread thread = new Thread(new OrderProcessorThread());
            thread.start(); // 启动消费者线程
        }
    }

    private class OrderProcessorThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Order order = orderQueue.take(); // 从队列中取出订单,如果队列为空则会阻塞
                    processOrder(order); // 处理订单
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }

        private void processOrder(Order order) {
            // 处理订单的逻辑
            System.out.println("Processing order: " + order.getId());
            // 模拟处理时间
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("Order processed: " + order.getId());
        }
    }
}

public class Order {
    private int id;

    public Order(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

public class Main {
    public static void main(String[] args) {
        OrderProcessor orderProcessor = new OrderProcessor(5); // 设置最大并发处理能力为5
        orderProcessor.startProcessing();

        // 模拟提交订单
        for (int i = 1; i <= 10; i++) {
            try {
                orderProcessor.submitOrder(new Order(i));
                System.out.println("Order submitted: " + i);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

在上述代码中,OrderProcessor类使用LinkedBlockingQueue作为订单队列,通过构造方法传入最大并发处理能力maxConcurrency来设置队列的容量。submitOrder方法用于将订单放入队列中,如果队列已满,则会阻塞。startProcessing方法启动消费者线程,每个线程从队列中取出一个订单进行处理。processOrder方法模拟处理订单的逻辑,并通过Thread.sleep方法模拟订单处理的时间。Main类中的main方法模拟提交订单的过程,可以看到当订单数量超过最大并发处理能力时,部分订单会被阻塞,直到有空闲的处理线程。

以下是一个使用BlockingQueue实现多线程之间协作和数据传递的Java代码示例:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class DataProcessor {
    private BlockingQueue<Integer> dataQueue;

    public DataProcessor() {
        dataQueue = new LinkedBlockingQueue<>();
    }

    public void produceData() {
        for (int i = 1; i <= 10; i++) {
            try {
                dataQueue.put(i); // 将数据放入队列
                System.out.println("Producing data: " + i);
                Thread.sleep(1000); // 模拟数据生产时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public void consumeData() {
        while (true) {
            try {
                int data = dataQueue.take(); // 从队列中取出数据,如果队列为空则会阻塞
                System.out.println("Consuming data: " + data);
                Thread.sleep(2000); // 模拟数据处理时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    public static void main(String[] args) {
        DataProcessor dataProcessor = new DataProcessor();

        Thread producerThread = new Thread(dataProcessor::produceData);
        Thread consumerThread = new Thread(dataProcessor::consumeData);

        producerThread.start();
        consumerThread.start();
    }
}

在上述代码中,DataProcessor类使用LinkedBlockingQueue作为数据队列。produceData方法用于生产数据,循环将数字1到10放入队列中,每放入一个数据会打印出相应的生产信息,并通过Thread.sleep方法模拟数据生产的时间。consumeData方法用于消费数据,循环从队列中取出数据,每取出一个数据会打印出相应的消费信息,并通过Thread.sleep方法模拟数据处理的时间。在main方法中,创建一个DataProcessor对象,然后创建一个生产者线程和一个消费者线程,分别调用produceData和consumeData方法,启动两个线程进行数据的生产和消费。通过使用BlockingQueue实现数据的生产和消费,可以实现多线程之间的协作和数据传递。

jenkins 构建日志收集到ES集群测试

ES 集群

1.https://www.bogotobogo.com/DevOps/Docker/Docker_Kubernetes_ElasticSearch_with_Helm_minikube.php

helm install elasticsearch elastic/elasticsearch -f ./values.yaml
helm install kibana elastic/kibana

(base) heidsoft@dev01:~$ cat values.yaml 
---
# Permit co-located instances for solitary minikube virtual machines.
antiAffinity: "soft"

# Shrink default JVM heap.
esJavaOpts: "-Xmx128m -Xms128m"

# Allocate smaller chunks of memory per pod.
resources:
  requests:
    cpu: "100m"
    memory: "512M"
  limits:
    cpu: "1000m"
    memory: "512M"

# Request smaller persistent volumes.
volumeClaimTemplate:
  accessModes: [ "ReadWriteOnce" ]
  storageClassName: "standard"
  resources:
    requests:
      storage: 100M

oauth2 与 jwt 的区别是什么

OAuth2和JWT是两种不同的身份验证和授权机制。

OAuth2是一个开放标准的授权协议,用于授权第三方应用程序访问用户资源。它允许用户通过授权服务器授权第三方应用程序访问其受保护的资源,而不需要与第三方应用程序共享其用户名和密码。OAuth2通过授权码、密码、客户端凭据、隐式和刷新令牌等授权方式,提供了一种安全、可扩展的身份验证和授权机制。

JWT(JSON Web Token)是一种开放标准的身份验证和授权机制,用于在不同的应用程序之间传输信息。它是一种基于JSON的轻量级安全传输协议,由三部分组成:头部、载荷和签名。JWT的载荷部分可以存储用户的身份信息和其他相关数据,如用户ID、权限等。JWT使用数字签名来验证数据的完整性和真实性。

两者的主要区别如下:

  1. 功能不同:OAuth2用于身份验证和授权,而JWT用于在应用程序之间传输信息。
  2. 应用范围不同:OAuth2适用于通过授权访问用户资源的场景,如第三方登录、授权访问API等。JWT适用于在不同应用程序之间传输信息,如单点登录、跨域身份验证等。
  3. 数据格式不同:OAuth2使用授权码、令牌等数据格式来实现授权机制。JWT使用JSON格式来传输信息,并使用数字签名来验证数据的完整性和真实性。
  4. 安全性不同:OAuth2提供了多种授权方式,可以根据需求选择适合的方式,但需要进行额外的配置和管理。JWT使用数字签名来验证数据的完整性和真实性,提供了一种简单而安全的传输方式。
  5. 使用场景不同:OAuth2适用于具有多个第三方应用程序和用户资源的场景,如社交媒体平台、API访问等。JWT适用于在不同应用程序之间传输信息的场景,如单点登录、跨域身份验证等。

综上所述,OAuth2和JWT是两种不同的身份验证和授权机制,各自适用于不同的场景和需求。在实际应用中,可以根据具体需求选择合适的机制来实现身份验证和授权。

netstat 命令技巧

说明:
netstat命令用于显示各种网络相关信息,如网络连接,路由表,接口状态 (Interface Statistics),masquerade 连接,多播成员 (Multicast Memberships) 等等。

语法:

  -a或--all   显示所有连线中的Socket。
  -A<网络类型>或--<网络类型>   列出该网络类型连线中的相关地址。
  -c或--continuous   持续列出网络状态。
  -C或--cache   显示路由器配置的快取信息。
  -e或--extend   显示网络其他相关信息。
  -F或--fib   显示FIB。
  -g或--groups   显示多重广播功能群组组员名单。
  -h或--help   在线帮助。
  -i或--interfaces   显示网络界面信息表单。
  -l或--listening   显示监控中的服务器的Socket。
  -M或--masquerade   显示伪装的网络连线。
  -n或--numeric   直接使用IP地址,而不通过域名服务器。
  -N或--netlink或--symbolic   显示网络硬件外围设备的符号连接名称。
  -o或--timers   显示计时器。
  -p或--programs   显示正在使用Socket的程序识别码和程序名称。
  -r或--route   显示Routing Table。
  -s或--statistice   显示网络工作信息统计表。
  -t或--tcp   显示TCP传输协议的连线状况。
  -u或--udp   显示UDP传输协议的连线状况。
  -v或--verbose   显示指令执行过程。
  -V或--version   显示版本信息。
  -w或--raw   显示RAW传输协议的连线状况。
  -x或--unix   此参数的效果和指定"-A unix"参数相同。
  --ip或--inet   此参数的效果和指定"-A inet"参数相同。
 
实例:
1.列出所有端口 netstat -a(包括监听和未监听的);列出所有tcp端口netstat -at;列出所有udp端口netstat -au

# netstat -a | more
 Active Internet connections (servers and established)
 Proto Recv-Q Send-Q Local Address           Foreign Address         State
 tcp        0      0 localhost:30037         *:*                     LISTEN
 udp        0      0 *:bootpc                *:*

Active UNIX domain sockets (servers and established)
 Proto RefCnt Flags       Type       State         I-Node   Path
 unix  2      [ ACC ]     STREAM     LISTENING     6135     /tmp/.X11-unix/X0
 unix  2      [ ACC ]     STREAM     LISTENING     5140     /var/run/acpid.socket
 
2.列出所有处于监听状态的 Sockets

# netstat -l
 Active Internet connections (only servers)
 Proto Recv-Q Send-Q Local Address           Foreign Address         State
 tcp        0      0 localhost:ipp           *:*                     LISTEN
 tcp6       0      0 localhost:ipp           [::]:*                  LISTEN
 udp        0      0 *:49119                 *:*
 
3.只列出所有监听tcp端口 netstat -lt;列出所有监听udp端口使用netstat -lu;列出所有监听UNIX端口使用netstat -lx

# netstat -lt
 Active Internet connections (only servers)
 Proto Recv-Q Send-Q Local Address           Foreign Address         State
 tcp        0      0 localhost:30037         *:*                     LISTEN
 tcp        0      0 *:smtp                  *:*                     LISTEN
 tcp6       0      0 localhost:ipp           [::]:*                  LISTEN
 
4.显示所有端口的统计信息 netstat -s;显示TCP或UDP端口的统计信息使用netstat -st 或 -su

# netstat -s
 Ip:
 11150 total packets received
 1 with invalid addresses
 0 forwarded
 0 incoming packets discarded
 11149 incoming packets delivered
 11635 requests sent out
 Icmp:
 0 ICMP messages received
 0 input ICMP message failed.
 Tcp:
 582 active connections openings
 2 failed connection attempts
 25 connection resets received
 Udp:
 1183 packets received
 4 packets to unknown port received.
 .....
 
5.在netstat 输出中显示 PID 和进程名称 netstat -p。netstat -p 可以与其它开关一起使用,就可以添加 “PID/进程名称” 到 netstat 输出中,这样 debugging 的时候可以很方便的发现特定端口运行的程序。

# netstat -pt
 Active Internet connections (w/o servers)
 Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
 tcp        1      0 ramesh-laptop.loc:47212 192.168.185.75:www        CLOSE_WAIT  2109/firefox
 tcp        0      0 ramesh-laptop.loc:52750 lax:www ESTABLISHED 2109/firefox
 
6. 在 netstat 输出中不显示主机,端口和用户名 (host, port or user)
当你不想让主机,端口和用户名显示,使用 netstat -n。将会使用数字代替那些名称,这样可以加速输出,因为不用进行比对查询。

# netstat -an
如果只是不想让这三个名称中的一个被显示,使用以下命令
# netsat -a --numeric-ports
# netsat -a --numeric-hosts
# netsat -a --numeric-users
 
7.持续输出 netstat 信息

# netstat -c  //netstat将每隔一秒输出网络信息。
 Active Internet connections (w/o servers)
 Proto Recv-Q Send-Q Local Address           Foreign Address         State
 tcp        0      0 ramesh-laptop.loc:36130 101-101-181-225.ama:www ESTABLISHED
 tcp        1      1 ramesh-laptop.loc:52564 101.11.169.230:www      CLOSING
 tcp        0      0 ramesh-laptop.loc:43758 server-101-101-43-2:www ESTABLISHED
 tcp        1      1 ramesh-laptop.loc:42367 101.101.34.101:www      CLOSING
 
8. 显示系统不支持的地址族 (Address Families)

# netstat --verbose  //在输出的末尾,会有如下的信息
netstat: no support for `AF IPX' on this system.
netstat: no support for `AF AX25' on this system.
netstat: no support for `AF X25' on this system.
netstat: no support for `AF NETROM' on this system.
 
9.显示核心路由信息 netstat -r

# netstat -r
 Kernel IP routing table
 Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
 192.168.1.0     *               255.255.255.0   U         0 0          0 eth2
 link-local      *               255.255.0.0     U         0 0          0 eth2
 default         192.168.1.1     0.0.0.0         UG        0 0          0 eth2
注意: 使用 netstat -rn 显示数字格式,不查询主机名称。
 
10.找出程序运行的端口。并不是所有的进程都能找到,没有权限的会不显示,使用 root 权限查看所有的信息。

# netstat -ap | grep ssh
 tcp        1      0 dev-db:ssh           101.174.100.22:39213        CLOSE_WAIT  -
 tcp        1      0 dev-db:ssh           101.174.100.22:57643        CLOSE_WAIT  -
找出运行在指定端口的进程
# netstat -an | grep ':80'
 
11. 显示网络接口列表

# netstat -i
 Kernel Interface table
 Iface   MTU Met   RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
 eth0       1500 0         0      0      0 0             0      0      0      0 BMU
 eth2       1500 0     26196      0      0 0         26883      6      0      0 BMRU
 lo        16436 0         4      0      0 0             4      0      0      0 LRU
显示详细信息,像是 ifconfig 使用 netstat -ie:
# netstat -ie
 Kernel Interface table
 eth0      Link encap:Ethernet  HWaddr 00:10:40:11:11:11
 UP BROADCAST MULTICAST  MTU:1500  Metric:1
 RX packets:0 errors:0 dropped:0 overruns:0 frame:0
 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
 Memory:f6ae0000-f6b00000
 
12.IP和TCP分析,查看连接某服务端口最多的的IP地址

# netstat -nat | grep "192.168.1.15:22" |awk '{print $5}'|awk -F: '{print $1}'|sort|uniq -c|sort -nr|head -20
18 221.136.168.36
3 154.74.45.242
2 78.173.31.236
2 62.183.207.98
2 192.168.1.14
2 182.48.111.215
2 124.193.219.34
2 119.145.41.2
2 114.255.41.30
1 75.102.11.99
 
13.查看TCP各种状态列表

# netstat -nat |awk '{print $6}'|sort|uniq
established)
Foreign
LISTEN
TIME_WAIT
ESTABLISHED
TIME_WAIT
SYN_SENT
先把状态全都取出来,然后使用uniq -c统计,之后再进行排序。
# netstat -nat |awk '{print $6}'|sort|uniq -c
143 ESTABLISHED
1 FIN_WAIT1
1 Foreign
1 LAST_ACK
36 LISTEN
6 SYN_SENT
113 TIME_WAIT
1 established)
 
14.分析access.log获得访问前10位的ip地址

# awk '{print $1}' access.log |sort|uniq -c|sort -nr|head -10

nginx 配置

ngcloud.conf

server {
    listen       80;
    server_name  www.ngcloud.cc;

    charset utf-8;
    access_log  /var/log/nginx/ngcloud.access.log  main;
   
    location / {
         proxy_pass   http://127.0.0.1:18080;
    }

    #配置一个静态web服务,web服务使用前端路由
    location /cmp {
        alias   /opt/ngcloud/dist;
        index  index.html index.htm;
    }
    
    #执行正则匹配,区分大小写,匹配多有,但符合.jpg .jpeg 等结尾的后缀时,执行该规则
    location  ~ .*\.(jpg|jpeg|gif|png|ico|css|js|pdf|txt)$ {
       root /opt/ngcloud/dist;
       expires 30d;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}


流式数据架构

流处理架构

  1. https://github.com/confluentinc/ksql
  2. https://maxwells-daemon.io/config/#general
  3. https://github.com/zendesk/maxwell
  4. https://cloud.tencent.com/developer/article/1384059?from=article.detail.1451228&areaSource=106000.1&traceId=Kw8kIGt3_4MB_sm99vl7f
  5. https://github.com/openark/orchestrator

ML

1 https://milvus.io/docs/overview.md
2. https://github.com/hwchase17/langchain

MPP架构

https://developer.baidu.com/article/detail.html?id=294354
https://zhuanlan.zhihu.com/p/148621151

clickhouse 数据模型

  1. https://hub.docker.com/r/yandex/clickhouse-server/
$ mkdir $HOME/some_clickhouse_database
$ docker run -d --name some-clickhouse-server --ulimit nofile=262144:262144 --volume=$HOME/some_clickhouse_database:/var/lib/clickhouse yandex/clickhouse-server 

数据分析

filebeat

root@dev01:/var/log/filebeat# cat /etc/filebeat/filebeat.yml
###################### Filebeat Configuration Example #########################

# This file is an example configuration file highlighting only the most common
# options. The filebeat.reference.yml file from the same directory contains all the
# supported options with more comments. You can use it as a reference.
#
# You can find the full configuration reference here:
# https://www.elastic.co/guide/en/beats/filebeat/index.html

# For more available modules and options, please see the filebeat.reference.yml sample
# configuration file.

# ============================== Filebeat inputs ===============================

filebeat.inputs:

# Each - is an input. Most options can be set at the input level, so
# you can use different inputs for various configurations.
# Below are the input specific configurations.

# filestream is an input for collecting log messages from files.
- type: filestream

  # Unique ID among all inputs, an ID is required.
  id: my-filestream-id

  # Change to true to enable this input configuration.
  enabled: true

  # Paths that should be crawled and fetched. Glob based paths.
  paths:
    - /var/log/nginx/*.log
    #- c:\programdata\elasticsearch\logs\*

  # Exclude lines. A list of regular expressions to match. It drops the lines that are
  # matching any regular expression from the list.
  # Line filtering happens after the parsers pipeline. If you would like to filter lines
  # before parsers, use include_message parser.
  #exclude_lines: ['^DBG']

  # Include lines. A list of regular expressions to match. It exports the lines that are
  # matching any regular expression from the list.
  # Line filtering happens after the parsers pipeline. If you would like to filter lines
  # before parsers, use include_message parser.
  #include_lines: ['^ERR', '^WARN']

  # Exclude files. A list of regular expressions to match. Filebeat drops the files that
  # are matching any regular expression from the list. By default, no files are dropped.
  #prospector.scanner.exclude_files: ['.gz$']

  # Optional additional fields. These fields can be freely picked
  # to add additional information to the crawled log files for filtering
  #fields:
  #  level: debug
  #  review: 1

# ============================== Filebeat modules ==============================

filebeat.config.modules:
  # Glob pattern for configuration loading
  path: ${path.config}/modules.d/*.yml

  # Set to true to enable config reloading
  reload.enabled: true

  # Period on which files under path should be checked for changes
  #reload.period: 10s

# ======================= Elasticsearch template setting =======================

setup.template.settings:
  index.number_of_shards: 1
  #index.codec: best_compression
  #_source.enabled: false


# ================================== General ===================================

# The name of the shipper that publishes the network data. It can be used to group
# all the transactions sent by a single shipper in the web interface.
#name:

# The tags of the shipper are included in their own field with each
# transaction published.
#tags: ["service-X", "web-tier"]

# Optional fields that you can specify to add additional information to the
# output.
#fields:
#  env: staging

# ================================= Dashboards =================================
# These settings control loading the sample dashboards to the Kibana index. Loading
# the dashboards is disabled by default and can be enabled either by setting the
# options here or by using the `setup` command.
#setup.dashboards.enabled: false

# The URL from where to download the dashboards archive. By default this URL
# has a value which is computed based on the Beat name and version. For released
# versions, this URL points to the dashboard archive on the artifacts.elastic.co
# website.
#setup.dashboards.url:

# =================================== Kibana ===================================

# Starting with Beats version 6.0.0, the dashboards are loaded via the Kibana API.
# This requires a Kibana endpoint configuration.
setup.kibana:

  # Kibana Host
  # Scheme and port can be left out and will be set to the default (http and 5601)
  # In case you specify and additional path, the scheme is required: http://localhost:5601/path
  # IPv6 addresses should always be defined as: https://[2001:db8::1]:5601
  #host: "localhost:5601"

  # Kibana Space ID
  # ID of the Kibana Space into which the dashboards should be loaded. By default,
  # the Default Space will be used.
  #space.id:

# =============================== Elastic Cloud ================================

# These settings simplify using Filebeat with the Elastic Cloud (https://cloud.elastic.co/).

# The cloud.id setting overwrites the `output.elasticsearch.hosts` and
# `setup.kibana.host` options.
# You can find the `cloud.id` in the Elastic Cloud web UI.
#cloud.id:

# The cloud.auth setting overwrites the `output.elasticsearch.username` and
# `output.elasticsearch.password` settings. The format is `<user>:<pass>`.
#cloud.auth:

# ================================== Outputs ===================================

# Configure what output to use when sending the data collected by the beat.

# ---------------------------- Elasticsearch Output ----------------------------
#output.elasticsearch:
  # Array of hosts to connect to.
  # hosts: ["localhost:9200"]

  # Protocol - either `http` (default) or `https`.
  #protocol: "https"

  # Authentication credentials - either API key or username/password.
  #api_key: "id:api_key"
  #username: "elastic"
  #password: "changeme"

# ------------------------------ Logstash Output -------------------------------
#output.logstash:
  # The Logstash hosts
  #hosts: ["localhost:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

  # Client Certificate Key
  #ssl.key: "/etc/pki/client/cert.key"

# ------------------------------ kafka output ----------------------------------
output.kafka:
  # initial brokers for reading cluster metadata
  hosts: ["192.168.21.129:9092"]
  #sasl.mechanism: scram-sha-256
  version: "0.10.2.1"
  # message topic selection + partitioning
  topic: 'senz'
  partition.round_robin:
    reachable_only: false

  required_acks: 1
  compression: gzip
  max_message_bytes: 1000000
        

# ================================= Processors =================================
processors:
  - add_host_metadata:
      when.not.contains.tags: forwarded
  - add_cloud_metadata: ~
  - add_docker_metadata: ~
  - add_kubernetes_metadata: ~

# ================================== Logging ===================================

# Sets log level. The default log level is info.
# Available log levels are: error, warning, info, debug
#logging.level: debug

# At debug level, you can selectively enable logging only for some components.
# To enable all selectors use ["*"]. Examples of other selectors are "beat",
# "publisher", "service".
#logging.selectors: ["*"]

# ============================= X-Pack Monitoring ==============================
# Filebeat can export internal metrics to a central Elasticsearch monitoring
# cluster.  This requires xpack monitoring to be enabled in Elasticsearch.  The
# reporting is disabled by default.

# Set to true to enable the monitoring reporter.
#monitoring.enabled: false

# Sets the UUID of the Elasticsearch cluster under which monitoring data for this
# Filebeat instance will appear in the Stack Monitoring UI. If output.elasticsearch
# is enabled, the UUID is derived from the Elasticsearch cluster referenced by output.elasticsearch.
#monitoring.cluster_uuid:

# Uncomment to send the metrics to Elasticsearch. Most settings from the
# Elasticsearch output are accepted here as well.
# Note that the settings should point to your Elasticsearch *monitoring* cluster.
# Any setting that is not set is automatically inherited from the Elasticsearch
# output configuration, so if you have the Elasticsearch output configured such
# that it is pointing to your Elasticsearch monitoring cluster, you can simply
# uncomment the following line.
#monitoring.elasticsearch:

# ============================== Instrumentation ===============================

# Instrumentation support for the filebeat.
#instrumentation:
    # Set to true to enable instrumentation of filebeat.
    #enabled: false

    # Environment in which filebeat is running on (eg: staging, production, etc.)
    #environment: ""

    # APM Server hosts to report instrumentation results to.
    #hosts:
    #  - http://localhost:8200

    # API Key for the APM Server(s).
    # If api_key is set then secret_token will be ignored.
    #api_key:

    # Secret token for the APM Server(s).
    #secret_token:


# ================================= Migration ==================================

# This allows to enable 6.7 migration aliases
#migration.6_to_7.enabled: true

logging.level: info
logging.to_files: true
logging.files:
  path: /var/log/filebeat
  name: filebeat
  keepfiles: 7
  permissions: 0644

clickhouse 消费kafka


create table if not exists nginx.jsonlog_prod (
    `time` String,
    `msec` String,
    `remote_addr` String,
    `domain` String,
    `request_method` String,
    `uri` String,
    `status` String,
    `bytes_sent` String,
    `request_length` String,
    `request_time` String,
    `upstream_bytes_received` String,
    `proxy_host` String,
    `upstream_addr` String,
    `upstream_status` String,
    `upstream_header_time` String,
    `upstream_connect_time` String,
    `app` String,
    `upstream_addr_jyg` String,
    `upstream_response_time` String,
    `api` String,
    `rewrite` String,
    `serverip` String
)engine=Kafka()
SETTINGS
kafka_broker_list = '192.168.21.129:9092',
kafka_topic_list = 'senz',
kafka_group_name = 'nginx',
kafka_format = 'JSONEachRow',
kafka_num_consumers = 2,
kafka_thread_per_consumer = 1,
kafka_max_block_size = 262020,
kafka_commit_every_batch = 1;



CREATE TABLE queue (
`time` String,
`msec` String,
`remote_addr` String,
`domain` String,
`request_method` String,
`uri` String,
`status` String,
`bytes_sent` String,
`request_length` String,
`request_time` String,
`upstream_bytes_received` String,
`proxy_host` String,
`upstream_addr` String,
`upstream_status` String,
`upstream_header_time` String,
`upstream_connect_time` String,
`app` String,
`upstream_addr_jyg` String,
`upstream_response_time` String,
`api` String,
`rewrite` String,
`serverip` String
) ENGINE = Kafka('192.168.21.129:9092', 'senz', 'nginx', 'JSONEachRow');



create table if not exists nginx.nginx_prod (
    `time` DateTime,
    `msec` Float64,
    `remote_addr` String,
    `host` String,
    `request_method` String,
    `uri` String,
    `status` UInt16,
    `bytes_sent` UInt32,
    `request_length` UInt32,
    `request_time` Float64,
    `upstream_bytes_received` UInt32,
    `proxy_host` String,
    `upstream_addr` String,
    `upstream_status` UInt16,
    `upstream_header_time` Float64,
    `upstream_connect_time` Float64,
    `app` String,
    `upstream_addr_jyg` String,
    `upstream_response_time` Float64,
    `api` String,
    `rewrite` String,
    `serverip` String
)engine=MergeTree()
partition by toYYYYMMDD(time)
order by time
TTL time + INTERVAL 24 HOUR;



CREATE MATERIALIZED VIEW nginx.queue_to_nginx_prod TO nginx.nginx_prod AS
SELECT
    toDateTime(substring(time,1,19)) as time,
    toFloat64OrZero(msec) as msec,
    remote_addr,
    domain as host,
    request_method,
    uri,
    toUInt16OrZero(status) as status,
    toUInt32OrZero(bytes_sent) as bytes_sent,
    toUInt32OrZero(request_length) as request_length,
    toFloat64OrZero(request_time) as request_time,
    toUInt32OrZero(upstream_bytes_received) as upstream_bytes_received,
    proxy_host,
    upstream_addr,
    toUInt16OrZero(upstream_status) as upstream_status,
    toFloat64OrZero(upstream_header_time) as upstream_header_time,
    toFloat64OrZero(upstream_connect_time) as upstream_connect_time,
    app,
    upstream_addr_jyg,
    toFloat64OrZero(upstream_response_time) as upstream_response_time,
    api,
    rewrite,
    serverip
FROM nginx.queue;



1e768b6a5ce0 :) select * from nginx_prod order by time desc limit 1 \G

SELECT *
FROM nginx_prod
ORDER BY time DESC
LIMIT 1

Query id: 56448515-c279-424c-9e12-9a3f7eb528d4

Row 1:
──────
time:                    2023-04-21 15:41:06
msec:                    1682062866.168
remote_addr:             127.0.0.1
host:                    
request_method:          GET
uri:                     /index.nginx-debian.html
status:                  200
bytes_sent:              859
request_length:          73
request_time:            0
upstream_bytes_received: 0
proxy_host:              
upstream_addr:           
upstream_status:         0
upstream_header_time:    0
upstream_connect_time:   0
app:                     
upstream_addr_jyg:       
upstream_response_time:  0
api:                     
rewrite:                 
serverip:    




SELECT
  host,
  api,
  app,
  status,
  quantilesTiming(0.50,0.90,0.95,0.99)(request_time*1000) as reqtime,
  stddevSamp(request_time) as stdreqtime,
  quantilesTiming(0.50,0.90,0.95,0.99)(upstream_bytes_received) as received,
  stddevSamp(upstream_bytes_received) as stdreceived,
  count() as n
FROM  nginx.nginx_prod
GROUP by
  host,
  api,
  app,
  status
ORDER by
  n desc;


  SELECT
  host,
  api,
  app,
  status,
  quantilesTiming(0.5, 0.9, 0.95, 0.99)(request_time * 1000) AS reqtime,
  stddevSamp(request_time) AS stdreqtime,
  quantilesTiming(0.5, 0.9, 0.95, 0.99)(upstream_bytes_received) AS received,
  stddevSamp(upstream_bytes_received) AS stdreceived,
  count() AS n
FROM nginx.nginx_prod
GROUP BY
  host,
  api,
  app,
  status
ORDER BY n DESC

Query id: 32f22f58-4096-45ff-8714-1cbcc3eaf1e2

┌─host─┬─api─┬─app─┬─status─┬─reqtime───┬─stdreqtime─┬─received──┬─stdreceived─┬──n─┐
│      │     │     │    200 │ [0,0,0,0] │          0 │ [0,0,0,0] │           0 │ 18 │
└──────┴─────┴─────┴────────┴───────────┴────────────┴───────────┴─────────────┴────┘

1 rows in set. Elapsed: 0.040 sec. 

主机异常模拟

1、模拟master主机进程挂掉
2、模拟master主机突然关机
3、模拟master 系统卡住(命令:echo c > /proc/sysrq-trigger)
4、模拟master 系统CPU负载高stress -c 64
5、模拟master 系统内存使用启stress --vm 20 --vm-bytes 6G --timeout 180                 # 120G内存,持续180秒
6、模拟master 系统IO很高stress --io 20

redis 使用

在Redis集群中使用认证密码

Redis默认配置是不需要密码认证的,也就是说只要连接的Redis服务器的host和port正确,就可以连接使用。这在安全性上会有一定的问题,所以需要启用Redis的认证密码,增加Redis服务器的安全性。


1. 修改配置文件
Redis的配置文件默认在/etc/redis.conf,找到如下行:

#requirepass foobared
去掉前面的注释,并修改为所需要的密码:

requirepass myPassword

2. 重启Redis
如果Redis已经配置为service服务,可以通过以下方式重启:

service redis restart
如果Redis没有配置为service服务,可以通过以下方式重启:

/usr/local/bin/redis-cli shutdown
/usr/local/bin/redis-server /etc/redis.conf

3. 登录验证
设置Redis认证密码后,客户端登录时需要使用-a参数输入认证密码,不添加该参数虽然也可以登录成功,但是没有任何操作权限。如下:

$ ./redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> keys *
(error) NOAUTH Authentication required.
使用密码认证登录,并验证操作权限:

$ ./redis-cli -h 127.0.0.1 -p 6379 -a myPassword
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "myPassword"
看到类似上面的输出,说明Reids密码认证配置成功。

除了按上面的方式在登录时,使用-a参数输入登录密码外。也可以不指定,在连接后进行验证:

$ ./redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> auth myPassword
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "myPassword"
127.0.0.1:6379> 

4. 在命令行客户端配置密码
前面介绍了通过�redis.conf配置密码,这种配置方式需要重新启动Redis。也可以通命令行客户端配置密码,这种配置方式不用重新启动Redis。配置方式如下:

127.0.0.1:6379> config set requirepass newPassword
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "newPassword"
注意:使用命令行客户端配置密码,重启Redis后仍然会使用�redis.conf配置文件中的密码。


5. 在Redis集群中使用认证密码
如果Redis服务器,使用了集群。除了在master中配置密码外,也需要在slave中进行相应配置。在slave的配置文件中找到如下行,去掉注释并修改与master相同的密码即可:

# masterauth master-password

mysql innodb

查询的本质是一种声明式语法,用于指定需要从数据源中检索哪些数据或执行哪些操作。它可以描述数据的特定属性、条件和限制,而无需指定具体的实现细节。

在给定的示例中,以下是每个术语的含义:

  • const:用于声明一个常量,表示所查询的数据将是不可更改的。
  • ref:表示引用,指定查询将返回一个对数据的引用,而不是实际的数据副本。
  • ref_or_null:表示引用或空值,指定查询将返回一个对数据的引用,或者如果数据不存在则返回空值。
  • range:表示范围,指定查询将返回满足特定范围条件的数据。
  • index:表示索引,指定查询将返回满足特定索引条件的数据。
  • all:表示所有,指定查询将返回所有可用的数据。
  • index_range:表示索引范围,指定查询将返回满足特定索引范围条件的数据。

这些术语可以根据具体的查询语言或数据库系统的语法和语义进行解释和使用。它们提供了一种描述查询操作的统一方式,使开发人员能够以更简洁、清晰和易于理解的方式编写查询。

定的MySQL命令和语句来表示和管理这些结构。以下是MySQL中表示InnoDB表空间、区和段的一些常见代码结构表示:

  1. 创建表空间:

    CREATE TABLESPACE tablespace_name
    ADD DATAFILE 'path/to/datafile.ibd'
    ENGINE=InnoDB;
    

    这个命令用于创建一个新的InnoDB表空间,指定了表空间的名称和数据文件的路径。

  2. 创建表并指定表空间:

    CREATE TABLE table_name (
      column1 data_type,
      column2 data_type,
      ...
    ) TABLESPACE tablespace_name;
    

    这个命令用于创建一个新的表,并将其关联到特定的InnoDB表空间。

  3. 调整表空间大小:

    ALTER TABLESPACE tablespace_name
    ADD DATAFILE 'path/to/new_datafile.ibd'
    ENGINE=InnoDB;
    

    这个命令用于调整表空间的大小,可以添加新的数据文件来扩展表空间的容量。

  4. 区的代码结构表示:
    在InnoDB中,区是由连续的数据页组成的。在代码中,可以通过使用内部的InnoDB数据字典来获取和管理区的信息。

  5. 段的代码结构表示:
    在InnoDB中,段是由一个或多个连续的区组成的。在代码中,可以使用InnoDB内部的数据字典和管理函数来获取和管理段的信息。

需要注意的是,InnoDB的内部结构和实现是高度复杂的,并且在不同的MySQL版本中可能会有一些差异。因此,具体的代码结构表示和管理方法可能会有所不同。上述示例提供了一些常见的MySQL代码结构表示,但具体情况可能需要根据实际需求和使用的MySQL版本进行调整和修改。

terraform 使用

terraform initterraform workspace new都是Terraform的命令,但是它们的功能是不同的。

terraform init是用来初始化一个Terraform工作目录。它会加载和安装所需的provider插件,并创建一个初始的后端配置。

terraform workspace new是用来创建一个新的workspace。在Terraform中,workspace可以用来管理不同的环境,如开发环境,测试环境,生产环境等。

因此,如果你只是想创建一个新的workspace,那么只需要执行terraform workspace new就可以了。但是如果你是在一个新的Terraform工作目录中工作,那么你可能还需要执行terraform init来进行初始化。

kdump

为什么centos7 开启kdump后的状态是 active (exited)

这是因为当你启动kdump服务时,它实际上是在为系统崩溃时准备好了一个内核转储环境,然后就退出了。所以,尽管你看到的状态是“active (exited)”,但这并不意味着kdump服务没有运行或出现了问题。相反,这意味着kdump服务已经成功地设置好了需要的环境,然后就退出了。

系统在正常运行时,kdump服务并不需要持续运行。只有当系统崩溃时,kdump服务才会被激活,然后捕获系统崩溃时的内核转储信息。

因此,如果你看到kdump服务的状态是“active (exited)”,那么这就意味着kdump服务已经成功地启动并准备好了。

当系统崩溃时,内核会触发Kdump服务,然后备用内核会启动并捕获系统的内存映像。这个内存映像通常被保存为一个文件,供管理员或开发人员用于分析系统崩溃的原因。

以下是Kdump服务的工作流程:

  1. 系统启动时,Kdump服务会加载备用内核和内存映像到保留的内存区域。

  2. 当系统崩溃时,系统内核会触发Kdump服务。

  3. 备用内核启动并开始捕获系统的内存映像。

  4. 内存映像被保存为一个文件,通常放在/var/crash目录下。

  5. 系统重启,管理员或开发人员可以查看这个文件,分析系统崩溃的原因。

Kdump服务的主要优点是它可以在系统崩溃时提供详细的信息,帮助开发人员和管理员找出问题的根源。然而,它也有一些缺点,比如需要预留一部分系统内存给备用内核和内存映像,这会降低系统的可用内存。此外,保存和分析内存映像文件需要一定的技术知识。

创建一个由systemd管理的服务并使其状态为active(exited),你可以按照以下步骤操作:

  1. 首先,创建一个新的systemd服务单元文件。例如,我们可以创建一个名为my_service.service的文件,放在/etc/systemd/system/目录下:
sudo nano /etc/systemd/system/my_service.service
  1. 在这个文件中,你需要定义服务的描述、执行的命令以及其他配置。例如:
[Unit]
Description=My Custom Service

[Service]
Type=oneshot
ExecStart=/path/to/your/command
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

在上面的例子中,服务类型(Type)被设置为oneshot,这意味着这个服务将会在执行完ExecStart指定的命令后退出。RemainAfterExit=yes这个选项会让systemd在服务进程退出后仍然认为这个服务是激活的。

  1. 保存并关闭文件。然后,你需要重新加载systemd的配置:
sudo systemctl daemon-reload
  1. 现在,你可以启动你的服务了:
sudo systemctl start my_service
  1. 如果你现在检查你的服务的状态,你应该会看到它的状态是active (exited)
sudo systemctl status my_service

请注意,这只是一个基本的示例,你可能需要根据你的具体需求来修改这个服务单元文件。

在Systemd服务单元文件中,Type字段用来指定启动类型,以下是一些可用的类型:

  1. simple:默认值,如果没有指定Type,那么就是这个类型。这种类型的服务在ExecStart指定的进程运行期间处于激活状态。

  2. forking:此类型用于传统的守护进程,这些进程在启动后会立即派生(fork)一个或多个子进程,然后父进程立即退出。

  3. oneshot:这种类型通常用于一次性的任务,也就是说,这个服务会在ExecStart指定的进程结束后变为非激活状态。如果设置了RemainAfterExit=yes,那么进程虽然已经退出,但是服务仍然被认为是激活的。

  4. dbus:这种类型的服务在DBus系统总线上取得一个名称后被认为是激活的。

  5. notify:这种类型的服务在启动完毕后会发送一个通知信号给systemd,然后systemd才会认为服务已经激活。

  6. idle:这种类型类似于simple,但是它会延迟启动进程,直到所有其他作业都调度完毕。

这些类型决定了systemd如何管理和监控服务进程,以及何时认为服务已经"启动完毕"。根据服务的特性和需求,选择合适的类型很重要。

To test our kdump configuration we will manually crash our system with below commands.

[root@cloud ~]# echo 1 > /proc/sys/kernel/sysrq ; echo c > /proc/sysrq-trigger

/proc/sys/kernel/sysrq和/proc/sysrq-trigger都是Linux内核的接口,用于控制Magic SysRq键的功能。

/proc/sys/kernel/sysrq接受的参数是0和1,其中1表示开启SysRq功能,0表示关闭。

/proc/sysrq-trigger接受的参数是一些字符,每个字符都对应了一个SysRq命令,这些命令包括:

  • 'b': 立即重新引导(重启)系统
  • 'c': 触发一个系统崩溃
  • 'd': 显示所有锁定的互斥锁
  • 'e': 发送TERM信号给所有进程,除了init
  • 'f': 调用OOM killer,对内存不足的情况进行紧急处理
  • 'h': 显示帮助信息,列出所有可用的SysRq命令
  • 'i': 发送KILL信号给所有进程,除了init
  • 'j': 对文件系统进行冻结,用于备份等操作
  • 'k': KILL所有在当前终端下运行的进程
  • 'l': 发送KILL信号给所有进程,包括init
  • 'm': 输出内存信息到控制台
  • 'n': 重新设置当前的nice值,用于调整进程优先级
  • 'o': 关闭系统(电源)
  • 'p': 输出当前的寄存器和标志到控制台
  • 'q': 强制所有CPU快速重启
  • 'r': 设置键盘模式为RAW,以便在X崩溃后恢复控制台
  • 's': 同步所有挂载的文件系统
  • 't': 输出任务列表到控制台
  • 'u': 重新挂载所有文件系统为只读
  • 'v': 强制回收内存
  • 'w': 输出当前任务的块IO信息
  • 'x': 用于调试,转储所有CPU的寄存器
  • '0'-'9': 设置loglevel,决定哪些等级的内核消息会被打印到控制台

请注意,这些命令需要root权限才能执行,并且不同的Linux发行版可能会禁用一些命令或者提供额外的命令,具体需要查阅相关文档。

Magic SysRq键是Linux内核中的一个特殊功能,它允许用户在系统运行出现问题时直接与内核进行交互,执行一些紧急恢复操作。

这个功能是通过键盘上的SysRq键(通常和Print Screen键共用一个键位)加上一些其他键来触发的。例如,按下Alt+SysRq+某个字母键,就可以执行特定的命令,如重新引导系统、同步硬盘、杀掉所有进程等。

Magic SysRq键的一大优点是它不受用户空间程序的影响,即使系统出现严重问题,如内存溢出、死锁等,只要内核还在运行,就能够通过Magic SysRq键来进行恢复。

需要注意的是,Magic SysRq键功能在一些系统中可能默认是关闭的,需要通过/proc/sys/kernel/sysrq接口来开启。

https://linux.web.cern.ch/centos7/docs/rhel/Red_Hat_Enterprise_Linux-7-Kernel_Crash_Dump_Guide-en-US.pdf
http://underpop.online.fr/l/linux/en/centos/s1-kdump-configuration.htm
https://help.aliyun.com/zh/ecs/how-do-i-configure-kdump-in-a-alibaba-cloud-linux-2-system
https://www.linuxtechi.com/how-to-enable-kdump-on-rhel-7-and-centos-7/
https://www.thegeekdiary.com/centos-rhel-7-how-to-configure-kdump/
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/ch-kdump

机器学习

Ubuntu GPU 驱动安装

#!/bin/bash

# install CUDA Toolkit v8.0
# instructions from https://developer.nvidia.com/cuda-downloads (linux -> x86_64 -> Ubuntu -> 16.04 -> deb (network))
CUDA_REPO_PKG="cuda-repo-ubuntu1604_8.0.61-1_amd64.deb"
wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/${CUDA_REPO_PKG}
sudo dpkg -i ${CUDA_REPO_PKG}
sudo apt-get update
sudo apt-get -y install cuda

# install cuDNN v6.0
CUDNN_TAR_FILE="cudnn-8.0-linux-x64-v6.0.tgz"
wget http://developer.download.nvidia.com/compute/redist/cudnn/v6.0/${CUDNN_TAR_FILE}
tar -xzvf ${CUDNN_TAR_FILE}
sudo cp -P cuda/include/cudnn.h /usr/local/cuda-8.0/include
sudo cp -P cuda/lib64/libcudnn* /usr/local/cuda-8.0/lib64/
sudo chmod a+r /usr/local/cuda-8.0/lib64/libcudnn*

# set environment variables
export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

ipvs 与 性能测试

MySQL 5.7.42中创建新用户并授予远程客户端访问权限

要在MySQL 5.7.42中创建新用户并授予远程客户端访问权限,您可以按照以下步骤操作:

  1. 以root用户身份登录到MySQL服务器。

  2. 创建新用户:

CREATE USER 'username'@'%' IDENTIFIED BY 'password';

username替换为您要创建的新用户的用户名,将password替换为该用户的密码。

  1. 授予新用户远程访问权限:
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' WITH GRANT OPTION;

这将授予新用户对所有数据库和表的完全访问权限,并允许他们使用GRANT命令授权其他用户。

  1. 刷新权限:
FLUSH PRIVILEGES;

这将使新的权限设置立即生效。

现在,您已经成功创建了一个新用户并授予了远程访问权限。其他客户端可以使用该用户名和密码连接到MySQL服务器。

在MySQL中,ALL权限表示授予用户所有可用的权限。它包括以下类型的权限:

  1. SELECT:允许用户查询表中的数据。
  2. INSERT:允许用户向表中插入新的数据。
  3. UPDATE:允许用户更新表中的数据。
  4. DELETE:允许用户删除表中的数据。
  5. CREATE:允许用户创建新的数据库或表。
  6. DROP:允许用户删除数据库或表。
  7. ALTER:允许用户修改数据库或表的结构。
  8. INDEX:允许用户创建或删除索引。
  9. GRANT OPTION:允许用户将自己拥有的权限授予其他用户。

WITH GRANT OPTION表示授予用户具有授权其他用户的权限。也就是说,用户被授予了将自己拥有的权限赋予其他用户的能力。这意味着该用户可以使用GRANT语句授予其他用户相同的权限。

在MySQL中,WITH GRANT OPTION可以有以下几种写法:

  1. WITH GRANT OPTION:这是最常见和标准的写法,表示授予用户具有授权其他用户的权限。

  2. WITH GRANT:这是WITH GRANT OPTION的简化写法,可以省略OPTION关键字。

  3. WITH GRANT OPTION TRUE:这是使用TRUE关键字的写法,表示授予用户具有授权其他用户的权限。

  4. WITH GRANT OPTION 1:这是使用1作为值的写法,表示授予用户具有授权其他用户的权限。

无论选择哪种写法,它们都具有相同的含义,即授予用户具有授权其他用户的权限。

如果在GRANT语句中没有包含WITH GRANT OPTION,则表示授予用户所有权限,但不包括授权其他用户相同权限的能力。

这意味着该用户可以拥有并使用所有权限,包括SELECT、INSERT、UPDATE、DELETE、CREATE、DROP、ALTER、INDEX等等,但不能使用GRANT语句将自己拥有的权限授予其他用户。换句话说,该用户只能使用自己拥有的权限,不能授权给其他用户相同的权限。

如果需要将授予的权限授权给其他用户,需要在GRANT语句中使用WITH GRANT OPTION关键字。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.