卷积神经网络(人马分类)

目录

正文:

1.数据集准备

2.模型建立

3.模型调用

注释:

一.ImageDataGenerator介绍

 二.flow_from_directory介绍

三.判断深度学习效果好坏(通过loss和val_loss比较)

四.测试图片格式转换问题

1.img_to_array()

2.expand_dims()

3.np.squeeze()

五.model.evaluate和model.predict的区别 

1.model.evaluate

2.model.predict


正文:

比如一个人马分类的例子

1.数据集准备

首先我们需要先下载人马数据集(如果是windows的话,先安装wget下载工具)

(注意wget下载后要放到项目工作路径下,例:

#测试数据集的下载命令(在pycharm中的Terminal命令行下输入)
wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/validation-horse-or-human.zip

#训练数据集的下载命令
wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/horse-or-human.zip 

然后把下载的数据移动到刚空文件夹tmp里,然后解压

在这里我们会遇到一个组件叫做imageDataGenerator

真实数据的特点

  • 图片尺寸大小不一,需裁剪成一样大小
  • 数据量比较大,不能一下子装入内存
  • 经常需要修改参数,例如输出的尺寸,增补图像拉伸等

所有这些事情手工编程都可以做到,但是用imageDataGenerator比较省事。

2.模型建立

模型训练代码:

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

#创建两个数据生成器,指定scaling范围0~1
train_datagen = ImageDataGenerator(rescale=1/255) #数据生成器介绍详见下面注释一,
validataion_datagen = ImageDataGenerator(rescale=1/255)#其实在这里就是归一标准化

#指向训练数据文件夹
train_generator =  train_datagen.flow_from_directory(#flow_from_directory参考注释二
          'F:/deeplearning/tmp/horse-or-human',#训练数据所在文件夹
          target_size=(150,150),#指定输出尺寸
          batch_size=32,
          class_mode='binary') #指定二分类

#指向测试数据文件夹
validation_generator = train_datagen.flow_from_directory(
          'F:/deeplearning/tmp/validation-horse-or-human',
          target_size=(150,150),
          batch_size=32,
          class_mode='binary')

#构建模型
model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(16,(3,3), activation='relu',input_shape=(150,150,3)),#16个3*3的过滤器,这是一个卷积层,详细参考https://keras.io/zh/layers/convolutional/
        tf.keras.layers.MaxPooling2D(2,2),#最大池,对于空间数据的最大池化,详细参考https://keras.io/zh/layers/pooling/
        tf.keras.layers.Conv2D(32,(3,3),activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64,(3,3),activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Flatten(),#这里不用写input_shape的原因是在第一个卷积层中就已经有过对特征图输入约束的声明了
        tf.keras.layers.Dense(512,activation='relu'),
        tf.keras.layers.Dense(1,activation='sigmoid')#因为是二分类,所以用sigmoid
])

#编译模型
from tensorflow.keras.optimizers import RMSprop 
'''
常见的优化方法有SGD,Momentum,AdaGrad,RMSProp,Adam
RMSprop是一种自适应学习率方法。RMSprop仅仅是计算对应的平均值,算法学习率下降相对AdaGrad较为缓慢吧
'''
model.compile(loss='binary_crossentropy',
                optimizer=RMSprop(lr=0.001),
                metrics=['accuracy'])
'''
损失函数(loss)是用来估量模型的预测值f(x)与真实性Y的不一致程度,损失函数越小,一般就代表模型的鲁棒性越好,正是损失函数指导了模型的学习。损失函数还是比较多,这里就不赘述了可以参考https://www.cnblogs.com/smuxiaolei/p/8662177.html
'''

#训练模型
history = model.fit( #在CV-1已经介绍过这个函数
          train_generator,
           epochs=15,
          verbose=1,
           validation_data = validation_generator,
           validation_steps=8)
#模型保存
model.save('E:/my_model.h5')

#训练后的模型精度

import matplotlib.image as mping
import matplotlib.pyplot as plt

'''
loss是训练损失,val_loss是测试损失,
accuracy是训练数据的精度,val_accuracy是测试数据的精度
深度学习效果好坏如何通过这两个参数发现,请看下面注释三
'''

accuracy = history.history['accuracy']
var_accuracy = history.history['val_accuracy']
loss = history.history['loss']
val_loss=history.history['val_loss']

'''
举例:range(5)能产生一组0到5的list
这里的accuracy是一个数组,len能拿到这个数组的长度
range(数组)能拿到要画的误差图的横坐标
'''
epochs=range(len(accuracy))

plt.plot(epochs, loss,'r',"Training loss")
plt.plot(epochs,val_loss,'b',"Validation Loss")
plt.figure()
plt.show()

这是跑完之后模型训练的结果。

这个图将成为我们分析模型是否合理的重要指标(可能陷入局部最优,过拟合等等),所以这个图应该好好分析。

3.模型调用

从图中我们看出训练的效果还是可以接受的。但是也不是很理想,因为我们建立的神经网络模型参数还没有进行优化,在CV-3文章中将对参数进行优化。

接下来我们再对模型进行调用(在之前代码中已经进行了模型的保存)


#模型预测
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
from tensorflow import keras
import os
#调用模型
#重新创建完全相同的模型,包括其权重和优化程序


model = keras.models.load_model('E:/my_model.h5')

#显示网络结构
model.summary()

#验证模型
path1 = 'F:/deeplearning/tmp/validation-horse-or-human/horses/horse1-000.png'
path2 = 'F:/deeplearning/tmp/validation-horse-or-human/humans/valhuman01-00.png'
path3 = 'E:/289821395323715657.jpg'
path4 = 'E:/data.jpg'
img = image.load_img(path4,target_size=(150,150)) #加载图像
print(type(img)) #这里打印的结果是<class 'PIL.Image.Image'>
x = image.img_to_array(img) #对于x的变换请详看注释四
x = np.expand_dims(x,axis=0)

pclass = model.predict(x) #对于predict和evaluate的区别请详看注释五
print(pclass)#查看打印出来的预测结果
if pclass >= 1:
    print('我们识别出来的是个'+'人')
else:
    print('我们识别出来的是个' + '马')


plt.imshow(img)
plt.show()

在这里准备了四张图片,经过验证,我们的模型还是能够达到理想效果的。

梯度下降优化方法比较的论文:

An overview of gradient descent optimization algorithms

注释:

一.ImageDataGenerator介绍

keras.preprocessing.image.ImageDataGenerator(featurewise_center=False,samplewise_center=False,featurewise_std_normalizition=False,samplewise_std_normalization=False,zca_whitening=False,zca_epsilon=1e-6,rotation_range=0.,width_shift_range=0.,height_shift_range=0.,shear_range=0.,zoom_range=0.,channel_shift_range=0.,fill_mode='nearest',cval=0.,horizontal_filp=False,rescale=None,preprocessing_function=None,data_format=K.image_data_format())

作用:用以生成一个batch的图像数据,支持实时数据提升。训练时该函数会无限生成数据,直到达到规定的epoch次数为止。

参数:

  • featurewise_center:布尔值,使输入数据集中去中心化(均值为0),按feature执行
  • samplewise_center:布尔值,使输入数据的每个样本均值为0
  • featurewise_std_normalization:布尔值,将输入除以数据集的标准差以完成标准化,按feature执行
  • samplewist_std_normalization:布尔值,讲输入的每个样本除以其自身的标准差
  • zca_whitening:布尔值,对输入数据施加ZCA白化
  • zca_epsilon:ZCA使用的eposilon,默认1e-6
  • rotation_range:整数,数据提升时图片随机转动的角度
  • width_shift_range:浮点数,图片宽度的某个比例,数据提升时图片水平偏移的幅度
  • height_shift_range:浮点数,图片高度的某个比例,数据提升时图片竖直偏移的幅度
  • shear_range:浮点数,剪切强度(逆时针方向的剪切变换角度),是用来进行剪切变换的程度
  • zoom_range:浮点数或形如[lower,upper]的列表,随机缩放的幅度,若为浮点数,则相当于[lower,upper]=[1-zoom_range,1+zoom_range],用来进行随机的放大
  • channel_shift_range:浮点数,随机通道偏移的幅度
  • fill_mode: 'constant','nearest','reflect'或'wrap'之一,当进行变换时超出边界的点将根据本参数给定的方法进行处理
  • cval:浮点数或整数,当fill_mode=constant时,指定要向超出边界的点填充的值。
  • horizontal_filp:布尔值,进行随机水平翻转。随机的对图片进行水平翻转,这个参数适用于水平翻转不影响图片语义的时候
  • vertical_filp:布尔值,进行随机竖直翻转。
  • rescale:值将在执行其他处理前乘到整个图像上,我们的图像在RGB通道都是0~255的整数,这样的操作可能使图像的值过高或过低,所以我们将这个值定为0~1之间的数。
  • preprocessing_funtion:将被应用于每个输入的函数。该函数将在任何其他修改之前运行。该函数接受一个参数,为一张图片(秩为3的numpy array),并且输出一个具有相同shape的numpy array
  • date_format:字符串,"channel_first"或“channel_last"之一,代表图像的通道维的位置。该参数是Keras 1.x中的image_dim_ordering,”channel_last"对应原本的”tf","channel_first"对应原本的”th"。以128*128的RGB图像为例,“channel_first"应将数据组织为(3,128,128),而”channel_last"应将数据组织为(128,128,3)。该参数的默认值是~/.keras/keras.json中设置的值;若从未设置过,则为"channel_last"。

例子:

dategen = ImageDateGenerator(
rotation_range=10,#图片随机翻转的角度
width_shift_range=0.2,#图片随机水平偏移的幅度
height_shift_range=0.2,#图片随机竖直偏移的幅度
rescale=1./255,#执行其他处理前乘到整个图象上
shear_range=0.2,#剪切强度
zoom_range=0.2,#随机放大
horizontal_filp=True,#随机水平翻转
fill_mode='nearest')
 

 二.flow_from_directory介绍

flow_from_directory(directory)

作用:以文件夹路径为参数,生成经过数据提升/归一化后的数据,在一个无限循环中无限产生batch数据

参数:

  • directory:目标文件夹路径,对于每一个类该文件夹都要包含一个子文件夹,子文件夹中任何PNG、BNP、PPM的图片都会被生成器使用
  • target_size:整数tuple,默认为(256,256),图像将被resize成该尺寸
  • color_mode:颜色模式,为"grayscale","rgb"之一,默认为"rgb",代表这些图片是否会被转换为单通道或三通道的图片
  • classes:可选参数,为子文件夹的列表,如['dogs','cats']默认为None,若未提供,则该类别列表将从directory下的子文件夹名称/结构自动推断。每一个子文件夹都会被认为是一个新的类。(类别顺序将按照字母表顺序映射到标签值)。通过属性class_indices可获得文件夹名与类的序号的对应字典
  • class_mode:"categorical","binary","sparse"或None之一,默认为”categorical",该参数决定了返回的标签数组的形式,"categorical"会返回2D的one-hot编码标签(one hot编码进行数据的分类更准确,许多机器学习算法无法直接用于数据分类。数据的类别必须转换成数字,对于分类的输入和输出变量都是一样的,当输出变量使用one-hot编码时,它可以提供比单个标签更准确的一组预测),"binary"返回1D的二值标签,"sparse"返回1D的整数标签,如果为None则不返回任何标签,生成器将仅仅生成batch数据,这种情况在使用model.predict_generator()和model.evaluate_generator()等函数时会用到。
  • batch_size:batch数据的大小,默认32
  • shuffle:是否打乱数据,默认为True
  • seed:可选参数,打乱数据和进行变换时的随机数种子
  • save_to_dir:None或字符串,该参数能让你将提升后的图片保存起来,用以可视化
  • save_prefix:字符串,保存提升后图片时使用的前缀,仅当设置了save_to_dir时生效
  • save_format:"png"或"jpeg"之一,指定保存图片的数据格式,默认"jpeg"
  • flollow_links:是否访问子文件夹中的软链接

例子:


from tensorflow.keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    fill_mode='constant'
)
gener = datagen.flow_from_directory(r'F:\deeplearning\tmp\horse-or-human',
                                    batch_size=3,
                                    shuffle=False,
                                    save_to_dir=r'F:\deeplearning\tmp\train_result',
                                    save_prefix='trans_',
                                    save_format='jpg'
                                    )
for i in range(3):
    gener.next()

   结果:

         

结果解析:

之前

 与之前的相比,这个数据生成器确实把图形做了一些随机变换(注意我们没打乱顺序,方便比较变换前和变换后),因为batch_size是3,range是3,所以结果也应该是9张,然后我们发现变换后的结果确实是9张。

注意:

directory不需要你写那种directory='你的数据目录',直接写数据目录即可。

三.判断深度学习效果好坏(通过loss和val_loss比较)

train loss比test loss还高的话,一般是训练集的样本不足够,使得我们无法获得充分的图像特征,而测试集样本比较少,准确度容易高。

train loss不断下降,test loss不断下降,说明网络仍在学习(最好的)

train loss不断下降,test loss趋于不变,说明网络过拟合;(max pool或者正则化)

train loss趋于不变,test loss不断下降。说明数据集100%有问题(检查正则化)

train loss趋于不变,test loss趋于不变,说明学习遇到瓶颈,需要减小学习率或批量数目(减小学习率)

train loss不断上升,test loss不断上升,说明网络结构设计不当,训练超参数设置不当,数据集经过清洗等问题(最不好的情况)

四.测试图片格式转换问题

在这里我们通过load_img方法(指定图像路径读取图像)读取后的图像是PIL Image的实例,并不是Numpy数据(我们可以predict的输入数据需要是Numpy)这时候我们就需要通过img_to_array()方法转化为Numpy,读取完图像是三维向量,而模型输入要求是四维,所以我们需要通过expand_dims()方法扩展维度。

1.img_to_array()

作用:把numpy矩阵中的整数转换成浮点数

举例:

转换前:
[[ 3  3  3 ...  5  5  5]
 [ 3  3  3 ...  5  5  5]
 [ 3  3  3 ...  5  5  5]
 ...
 [ 3  3  3 ... 12 11 10]
 [ 3  3  3 ... 12 11 10]
 [ 3  3  3 ... 12 11 10]]
转换后:
[[ 3.  3.  3. ...  5.  5.  5.]
 [ 3.  3.  3. ...  5.  5.  5.]
 [ 3.  3.  3. ...  5.  5.  5.]
 ...
 [ 3.  3.  3. ... 12. 11. 10.]
 [ 3.  3.  3. ... 12. 11. 10.]
 [ 3.  3.  3. ... 12. 11. 10.]]

接下来的两个方法是对数组的维度进行增删操作,以使数组维度相匹配。

2.expand_dims()

作用: 在指定轴axis上增加数组a的一个维度,即在第"axis"维,加一个维度出来,原先在"axis"左边的维度保持位置不变,在“axis"右边的维度整体右移。

注意:该函数不改变输入数组a,而是产生一个新数组,新数组中的元素与原数组完全相同

举例:

例子1
代码:
import numpy as np

a = np.array([[[1,2,3],[4,5,6]]])
print(a.shape)#返回矩阵的规模,在这里是1个二维数组,二维数组里有两个一维数组,一维数组中有三列,所以是 1 2 3 
print('------------------------------------------------')
# np.expand_dims(a, axis=0)表示在0位置添加数据
b = np.expand_dims(a,axis=0)
print(b.shape)
print('------------------------------------------------')
# np.expand_dims(a, axis=1)表示在1位置添加数据
c = np.expand_dims(a,axis=1)
print(c.shape)
print('------------------------------------------------')
# np.expand_dims(a, axis=2)表示在2位置添加数据
d = np.expand_dims(a,axis=2)
print(d.shape)
print('------------------------------------------------')
# np.expand_dims(a, axis=3)表示在3位置添加数据
e = np.expand_dims(a,axis=3)
print(e.shape)
print('------------------------------------------------')

运行结果:
(1, 2, 3)
------------------------------------------------
(1, 1, 2, 3)
------------------------------------------------
(1, 1, 2, 3)
------------------------------------------------
(1, 2, 1, 3)
------------------------------------------------
(1, 2, 3, 1)
------------------------------------------------
例子2
假设三维数组a的shape是(m, n, c),则
np.expand_dims(a, axis=0)表示在a的第一个维度上增加一个新的维度,而其他维度整体往右移,最终得到shape为(1, m, n, c)的新数组,新数组中的元素与原数组完全相同。
代码
import numpy as np

a = np.reshape(list(range(24)), (2, 3, 4))
a_new = np.expand_dims(a, axis=0)
print('a =', a)
print('a_new =', a_new)
print('a.shape = ', a.shape)
print('a_new.shape = ', a_new.shape)
输出结果:
a = [[[ 0  1  2  3]
      [ 4  5  6  7]
      [ 8  9 10 11]]

     [[12 13 14 15]
      [16 17 18 19]
      [20 21 22 23]]]
      
a_new = [[[[ 0  1  2  3]
           [ 4  5  6  7]
           [ 8  9 10 11]]

          [[12 13 14 15]
           [16 17 18 19]
           [20 21 22 23]]]]
a.shape =  (2, 3, 4)
a_new.shape =  (1, 2, 3, 4)

3.np.squeeze()

squee(a,axis=None)

作用:删除输入数组a中维度为1的维度,并返回新的数组,新数组的元素与原数组a完全相同

举例:

>>> a = np.array([[[0], [1], [2]]])
>>> a.shape
(1, 3, 1)

# 未指定axis,则删除所有维度为1的维度
>>> np.squeeze(a)
[0, 1, 2]
>>> np.squeeze(a).shape
(3,)

# 指定axis=0,则删除该维度
>>> np.squeeze(a, axis=0)
[[0]
 [1]
 [2]]
>>> np.squeeze(a, axis=0).shape
(3, 1)

# 指定axis=2,则删除该维度
>>> np.squeeze(a, axis=2)
[[0 1 2]]
>>> np.squeeze(a, axis=2).shape
(3, 1)

# 同时指定axis=0和axis=2,则删除这两个维度
>>> np.squeeze(a, axis=(0, 2))
[0 1 2]
>>> np.squeeze(a, axis=(0, 2)).shape
(3,)

# 对于指定的axis,其维度必定为1,否则会报错
>>> np.squeeze(a, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size not equal to one

五.model.evaluate和model.predict的区别 

1.model.evaluate

Model.evaluate(
    x=None,
    y=None,
    batch_size=None,
    verbose=1,
    sample_weight=None,
    steps=None,
    callbacks=None,
    max_queue_size=10,
    workers=1,
    use_multiprocessing=False,
    return_dict=False,
)

 参数:

  • x:输入数据
  • y:输入标签
  • batch_size:批次大小
  • verbose:0不显示进度条,1为显示进度条
  • sample_weight:测试样本的可选Numpy权重数组,用于对损失函数加权
  • steps:样本批次
  • callbacks:评估期间需要应用的回调列表
  • max_queue_size:生成器队列的最大大小
  • workers:执行期间使用的进程数
  • use_multiprocessing:如果为True,则使用基于进程的线程
  • return_dict:如果为True,loss和metric结果将会作为词典(dict)返回,如果为False,他们 将会被返回为一个list。

返回值:

  • 损失值:网络在训练数据上的损失(预测值和实际值之间的差距),该值和编译模型时选择的损失有关
  • 精度:准确率(成功数量与总数据量的比值)
  • 返回格式:['loss','accuracy'] 

2.model.predict

Model.predict(
    x,
    batch_size=None,
    verbose=0,
    steps=None,
    callbacks=None,
    max_queue_size=10,
    workers=1,
    use_multiprocessing=False,
)

 参数:

  • x:输入数据
  • 其他参数同上

返回值:输出输入数据的预测结果,需要自己手动比较 

  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SAP Process Orchestration The Comprehensive Guide, 2nd Edition SAP流程编制综合指南 1 Introduction to SAP Process Orchestration 1.1 Historical Overview and Evolution 1.1.1 SAP Process Integration 1.1.2 SAP Composition Environment 1.1.3 SAP Process Orchestration 1.1.4 SAP Process Orchestration 7.5 Highlights 1.2 SAP Process Orchestration Components 1.2.1 SAP Process Integration 1.2.2 Business Process Management 1.2.3 Business Rules Management 1.3 Architectural Overview and Positioning 1.3.1 SAP Process Orchestration Positioning 1.3.2 SAP NetWeaver Application Server for Java: System Architecture 1.3.3 SAP NetWeaver AS Java System Logical Layers 1.4 Installation Options 1.4.1 Case 1: SAP Process Integration Dual Stack 1.4.2 Case 2: SAP PI Dual Stack and SAP Composition Environment in Separate Installations 1.4.3 Case 3: SAP PI Single Stack and SAP Composition Environment in Separate Installations 1.4.4 Case 4: SAP PO—SAP PI and SAP Composition Environment in a Single Installation 1.5 Summary 2 Administration and Development Tools 2.1 SAP Process Orchestration Tools 2.1.1 Enterprise Services Repository 2.1.2 Integration Directory 2.1.3 System Landscape Directory 2.1.4 Configuration and Monitoring 2.2 SAP NetWeaver Administrator 2.2.1 Availability and Performance 2.2.2 Operations 2.2.3 Configuration 2.2.4 Troubleshooting 2.2.5 SOA 2.3 SAP NetWeaver Developer Studio 2.3.1 Use and Download 2.3.2 SAP Process Orchestration and SAP NetWeaver Developer Studio 2.4 Summary Part II Advanced Adapter Engine Extended (AEX) 3 Configuring the System Landscape Directory 3.1 System Landscape Directory Components and Features 3.1.1 Landscape 3.1.2 Software Catalog 3.1.3 Development 3.2 Registering Systems to the System Landscape Directory 3.2.1 Connecting to ABAP-Based Systems 3.2.2 Connecting to Java-Based Systems 3.2.3 Connecting to Other Systems 3.3 Administration of the System Landscape Directory 3.3.1 Server 3.3.2 Data and Content 3.4 System Landscape Directory Strategies 3.4.1 Manual Export and Import of Data 3.4.2 Automatic Bridge Forwarding 3.4.3 Full Automatic Synchronization 3.5 Tips and Tricks 3.5.1 Naming Convention 3.5.2 Keeping Your System Landscape Directory Catalogs Up to Date 3.5.3 Self-Registration of a Java-Based System with the SLD 3.5.4 Configuring Data Suppliers from One SLD to Another 3.5.5 Manual Export and Import of Data 3.5.6 Connecting the SLD to CTS+ to Facilitate the Export and Import of SLD Data 3.6 Exercise: Configuring the System Landscape Directory 3.6.1 Exercise Description 3.6.2 Exercise Solution Approach 3.6.3 Exercise Step-by-Step Solution 3.7 Summary 4 Working with the Enterprise Services Repository and Registry 4.1 Basic ES Repository Technical Concepts 4.1.1 Functional Blocks 4.1.2 First Steps in the Enterprise Services Repository 4.1.3 Service Interface 4.1.4 Integration Patterns: Stateful and Stateless Communication 4.1.5 Asynchronous versus Synchronous 4.1.6 Quality of Service 4.2 Design Objects 4.2.1 Software Component Versions 4.2.2 Folders 4.2.3 Namespaces 4.2.4 Mappings 4.2.5 Process Integration Scenario 4.2.6 Actions 4.3 Data Types and Message Types 4.3.1 Data Types 4.3.2 External Definitions 4.3.3 Message Type 4.3.4 Additional Design Objects 4.4 Exercise: Working with the ES Repository and Registry 4.4.1 Exercise Description 4.4.2 Exercise Solution Approach 4.4.3 Exercise Step-by-Step Solution 4.5 Summary 5 Working with the Integration Directory 5.1 Integration Directory Overview 5.2 Collaboration Profiles 5.2.1 Party 5.2.2 Communication Component 5.2.3 Communication Channel 5.2.4 Communication Component without a Party 5.3 Adapter Types 5.3.1 Technical Adapters to Enable Communication with SAP or Third-Party Systems 5.3.2 Application Adapters to Enable Communication with an SAP System 5.3.3 SAP Industry Adapters 5.3.4 Third-Party-Developed Adapters 5.4 Integrated Configuration 5.4.1 Inbound Processing 5.4.2 Receiver 5.4.3 Receiver Interfaces 5.4.4 Outbound Processing 5.5 The XI Message Protocol 5.6 Configuration Scenario 5.6.1 Creating a Configuration Scenario from Scratch (Manually) 5.6.2 Creating a Configuration Scenario from a Model 5.7 Value Mapping 5.7.1 If/Else Logic 5.7.2 Fixed Values 5.7.3 Value Mapping 5.8 Business-to-Business Integration 5.8.1 Business-to-Business On Premise 5.8.2 Business-to-Business Managed Services 5.8.3 Trading Partner Management 5.9 Axis Framework 5.10 Representational State Transfer Adapter 5.11 Message Alerting 5.11.1 Alert Rule Overview 5.11.2 Creating an Alert Rule 5.11.3 Editing or Deleting a Rule 5.12 Publish the Service in the Services Registry 5.13 Integration Directory Programming Interface (Directory API) 5.14 Exercise: Working with the Integration Directory 5.14.1 Exercise Description 5.14.2 Exercise Solution Approach 5.14.3 Exercise Step-by-Step Solution 5.15 Summary 6 Building an Integration Flow 6.1 SAP NetWeaver Developer Studio 6.1.1 Installing SAP NetWeaver Developer Studio 6.1.2 Setting Up SAP NetWeaver Developer Studio 6.1.3 Enterprise Integration Patterns and User-Defined Templates 6.2 Basics of Creating and Configuring an Integration Flow 6.2.1 Creating an iFlow 6.2.2 Configuring an iFlow 6.3 iFlow Example 6.3.1 Creating Products, Software Components, Business Systems, and Technical Systems in the SLD 6.3.2 Importing SLD Objects into the ES Repository in SAP NetWeaver Developer Studio 6.3.3 Create Enterprise Service Repository Objects 6.3.4 Create Directory Objects: Import Business Systems and Create iFlows 6.3.5 Testing the iFlow Scenario 6.3.6 Monitoring the Scenario 6.4 New Features of the Process Integration Designer 6.4.1 Export Objects from the Integration Designer 6.4.2 Automatically Deploy after Import 6.4.3 Version History and Deployment Status 6.5 Supporting Multiple Senders for Your iFlow 6.6 Exercise: Building an Integration Flow 6.6.1 Exercise Description 6.6.2 Exercise Solution Approach 6.6.3 Exercise Step-by-Step Solution 6.7 Summary 7 Administration and Monitoring in AEX 7.1 Administration 7.1.1 Central Administration Tool 7.1.2 SAP NetWeaver Administrator 7.1.3 SAP NetWeaver Application Server Java 7.1.4 SAP Process Integration Monitoring (pimon) 7.1.5 SAP Management Console 7.1.6 Config Tool 7.1.7 Administration Using Telnet 7.2 Monitoring 7.2.1 SAP NetWeaver Administrator 7.2.2 SAP Process Integration Local Monitoring 7.2.3 SAP PI Central Monitoring with SAP Solution Manager 7.2.4 Message Retention 7.2.5 User-Defined Message Search 7.3 Troubleshooting 7.3.1 Configuring Log and Traces 7.3.2 Using the Log Viewer 7.4 Summary 8 Migrating Interfaces from SAP PI Dual Stack to SAP PO 8.1 Migration Strategies 8.2 Migrating System Landscape Directory Content 8.2.1 Products 8.2.2 Software Components 8.2.3 Technical System 8.2.4 Business System 8.3 Migrating Enterprise Services Repository Content 8.3.1 Exporting Objects 8.3.2 Importing Objects 8.4 Migrating Integration Directory Content 8.4.1 Manually 8.4.2 Using the Migration Tool 8.5 Summary Part III Business Process Management and Composition 9 Introduction to SAP BPM and BPMN 2.0 9.1 Managing Business Processes 9.2 SAP Business Process Management 9.2.1 SAP BPM versus SAP Business Workflow 9.2.2 BPM before SAP BPM 9.2.3 SAP BPM Main Components 9.3 Business Process Model and Notation 2.0 9.3.1 Swimlanes 9.3.2 Artifacts 9.3.3 Flow Objects 9.3.4 Connections 9.4 Summary 10 Creating Your First SAP BPM Process 10.1 SAP BPM Positioning and Development Environment 10.1.1 Positioning 10.1.2 Setting Up Your Development Environment 10.2 Creating and Modeling an SAP BPM Process 10.2.1 Demonstration Scenario 10.2.2 Building an SAP BPM Process: Overview 10.2.3 SAP NetWeaver Developer Studio Perspective Concept 10.2.4 Create a Project in SAP NetWeaver Developer Studio 10.2.5 Creating a Process for Your BPMN 10.2.6 Creating a BPMN Model 10.3 Configuring the BPMN Model 10.3.1 Data Objects 10.3.2 Creating Data Structures 10.3.3 Importing XSD and WSDL 10.3.4 Process Pool Properties 10.3.5 BPMN Flow Objects 10.4 Flow Objects 10.4.1 Events 10.4.2 Tasks 10.4.3 Activities 10.4.4 Gateways 10.4.5 Artifacts 10.5 Build and Deploy Your Process 10.5.1 Steps for Building a Process 10.5.2 Steps for Deploying a Process 10.6 Advanced Mapping 10.6.1 Mappings 10.6.2 Options in Mapping Assignment 10.6.3 Automatic Mapping 10.6.4 Custom Functions 10.7 Implementing Error Handling 10.8 Combining SAP BPM and the AEX 10.8.1 Message from SAP BPM to the AEX 10.8.2 Message from the AEX to SAP BPM 10.8.3 Leverage an ES Repository Mapping in SAP BPM 10.9 Exercise: Creating an SAP Business Process Management Process 10.9.1 Exercise Description 10.9.2 Exercise Solution Approach 10.9.3 Exercise Step-by-Step Solution 10.10 Summary 11 Applying Advanced SAP BPM Concepts and Extensions 11.1 Service-Oriented Architecture Configuration 11.1.1 Configuration for an Automated Activity 11.1.2 Configuration for a Start Event or Intermediary Event 11.2 Testing and Running an SAP BPM Process 11.2.1 Process Repository Overview 11.2.2 Process Testing 11.3 Custom Enterprise Java Bean Functions 11.3.1 Create EJB and EAR Development Components 11.3.2 Create the Enterprise Java Bean 11.3.3 Build and Deploy 11.3.4 Create a New Enterprise Java Bean Function 11.4 Using the Claim Check Pattern 11.4.1 Create Interfaces 11.4.2 Create Mappings 11.4.3 Configure the Channel 11.4.4 Retrieve the Large Message from SAP BPM 11.4.5 Update the Status of the Large Message from SAP BPM 11.5 SAP BPM Application Programming Interface 11.5.1 Prerequisite to Using the SAP BPM API 11.5.2 Implementation Aspects and Examples 11.6 SAP Business Process Management OData 11.6.1 OData Services for Tasks and Task Data 11.6.2 Error Handling 11.7 Using the Push API to Access SAP BPM Lifecycle Events 11.7.1 Accessing Events through a Message Driven Bean 11.7.2 Accessing Events through a Java Message Service API 11.8 Debugging and Troubleshooting SAP BPM Processes 11.8.1 Place Breakpoints in the Process 11.8.2 Add a Debug Configuration 11.9 Tuning SAP BPM-Related Performance Parameters 11.10 Best Practices for Your SAP BPM Application 11.10.1 BPMN, Mapping, and Parallelism 11.10.2 Task Related 11.10.3 Gateways 11.10.4 Looping 11.10.5 Data Object 11.10.6 Correlation 11.10.7 Error Handling 11.10.8 Housekeeping 11.11 Exercise: Applying Advanced SAP BPM Concepts and Extensions 11.11.1 Exercise Solution Approach 11.11.2 Exercise Step-by-Step Solution 11.12 Summary 12 Combining SAP BPM and UI Technologies 12.1 Web Dynpro Java User Interface Technology 12.1.1 Generating a Web Dynpro User Interface 12.1.2 Post-Configuration Steps 12.2 Integrating SAPUI5 into an SAP BPM Process 12.2.1 SAPUI5 Technology Platform 12.2.2 Model-View-Controller Concept 12.2.3 SAPUI5 Components 12.2.4 Other SAPUI5 Concepts 12.2.5 Integration Steps 12.3 Other User Interface Technologies 12.3.1 Visual Composer 12.3.2 Adobe Offline Forms 12.3.3 Support for Custom User Interface Technologies 12.4 Summary 13 SAP Business Rules Management 13.1 How Business Rules Work 13.2 SAP Business Rules Management 13.2.1 Rules Composer 13.2.2 Rules Manager 13.2.3 Rules Engine 13.3 Modeling Business Rules with Rules Composer 13.3.1 Create the Rules Composer Development Component 13.3.2 Adding Context to the Rules 13.3.3 Creating a Ruleset 13.3.4 Flow Ruleset 13.4 Testing Business Rules 13.5 Best Practices for Modeling Business Rules 13.5.1 Separate Decision Logic from Other Types of Logic 13.5.2 Reuse and Extend before Building 13.6 Exercise: SAP Business Rules Management 13.6.1 Exercise Solution Approach 13.6.2 Exercise Step-by-Step Solution 13.7 Summary 14 Implementing Java Proxies 14.1 Java Proxy Concept and Considerations 14.2 Implementation Approaches 14.2.1 Outside-In Approach 14.2.2 Inside-Out Approach 14.3 Technical Implementation 14.3.1 Development Environment 14.3.2 Developing a Server Java Proxy 14.3.3 Developing a Client Java Proxy 14.4 Building an Orchestration 14.5 Exercise: Implementing Java Proxies 14.5.1 Exercise Solution Approach 14.5.2 Exercise Step-by-Step Solution 14.6 Summary 15 Administration and Monitoring Message Processing in SAP BPM 15.1 Monitoring 15.1.1 SAP Business Process Management System Overview 15.1.2 Process Repository 15.1.3 Process Management 15.1.4 Task Management 15.1.5 SAP BPM Inbox 15.1.6 Business Logs 15.1.7 SAP BPM Action Monitor 15.1.8 Process Troubleshooting 15.1.9 Rules Business Logs 15.1.10 SAP BPM Analytics Dashboard 15.2 Administration 15.2.1 Process Data Archiving 15.2.2 Log Viewer 15.3 Summary 16 Migrating ccBPM from SAP PI to SAP PO 16.1 Motivation for Migration 16.2 Migration Approach 16.2.1 Analyze the As-Is Integration Processes 16.2.2 Translate and Redesign 16.2.3 Export and Reuse Enterprise Services Repository Objects 16.2.4 Migrate and Adapt Configuration Scenarios 16.3 Recommendations 16.4 Summary Part IV Advanced Concepts 17 SAP Cloud Platform Integration for SAP PO 17.1 Enable Cloud Integration Content in SAP PO 17.2 Reusing Cloud Integration Content 17.2.1 Download Cloud Integration Content 17.2.2 Deploy the Cloud Integration Content 17.3 Monitoring 17.3.1 Monitoring the Integration Gateway Component 17.3.2 Monitoring Messages Related to the Deployment of Cloud Integration Content 17.4 Summary 18 Additional Components for SAP Process Orchestration 18.1 Component Model 18.1.1 Product 18.1.2 Software Components 18.1.3 Development Component 18.1.4 Dependencies among Development Components 18.1.5 Public Parts 18.2 SAP NetWeaver Development Infrastructure 18.2.1 Change Management Services 18.2.2 Design Time Repository 18.2.3 Component Build Service 18.3 SAP Composite Application Framework 18.3.1 Design Time Aspects 18.3.2 Runtime Aspects 18.4 Service Registry 18.5 Enhanced Change and Transport System 18.5.1 SAP PI-Related Transports 18.5.2 Transports for Non-SAP PI Java Objects 18.6 Exercise: Create an SWCV 18.6.1 Exercise Solution Approach 18.6.2 Exercise Step-by-Step Solution 18.7 Summary 19 Landscape Setup Considerations 19.1 Java System Configuration 19.1.1 Java Sizing and Setup Considerations 19.1.2 Java System Architecture 19.1.3 Java Central Services 19.1.4 Java Parameter Tuning 19.2 Handling Certificates 19.2.1 Certificate Key Storage 19.2.2 Encryption of Message Content on Database Level 19.3 Housekeeping 19.3.1 Archiving 19.3.2 Deletion 19.3.3 Restarting 19.3.4 Recovery 19.4 Monitoring 19.4.1 Runtime Workbench 19.4.2 Wily Enterprise Manager 19.4.3 SAP Management Console 19.4.4 SAP Solution Manager Monitoring 19.4.5 Tracing 19.4.6 JVMMON 19.5 Summary A Orchestration Outlook A.1 SAP API Management A.2 SAP Cloud Platform Integration A.2.1 Features and Facts Overview of SAP Cloud Platform Integration A.2.2 Development Guide: Getting Started A.2.3 Monitoring A.3 The Integration Advisor A.3.1 Interface Specifications: Advice from the Advisor A.3.2 Mapping Guideline A.3.3 Runtime A.3.4 Testing A.4 SAP Cloud Platform Workflow as a Service A.4.1 Workflow Service A.4.2 Workflow Modeling A.4.3 SAP Cloud Platform Business Rules A.4.4 Workflow Tasks Management A.4.5 Integration 官方出品,英文原版,可编辑带导航非影印版(总计1866页)
Contents About the Author...............................................................................................xix About the Technical Reviewer and Contributing Author.................xxi Chapter1 Apache and the Internet..............................................1 Apache: The Anatomy of a Web Server.........................................................1 The Apache Source .............................................................................................1 The Apache License............................................................................................1 Support for Apache.............................................................................................2 How Apache Works..............................................................................................3 The Hypertext Transfer Protocol..................................................................7 HTTP Requests and Responses..........................................................................7 HTTP Headers...................................................................................................12 Networking and TCP/IP......................................................................................13 Definitions.........................................................................................................13 Packets and Encapsulation...............................................................................14 ACKs, NAKs, and Other Messages....................................................................15 The TCP/IP Network Model.............................................................................16 Non-IP Protocols...............................................................................................19 IP Addresses and Network Classes...................................................................19 Special IP Addresses..........................................................................................20 Netmasks and Routing......................................................................................21 Web Services: Well-Known Ports......................................................................23 Internet Daemon: The Networking Super Server...........................................24 The Future: IPv6................................................................................................25 Networking Tools...............................................................................................26 Server Hardware...................................................................................................29 Supported Platforms.........................................................................................29 Basic Server Requirements...............................................................................30 Memory..............................................................................................................31 Network Interface..............................................................................................32 Internet Connection.........................................................................................32 Hard Disk and Controller.................................................................................33 Operating System Checklist.............................................................................33 Redundancy and Backup..................................................................................34 Specific Hardware Solutions............................................................................35 Get Someone Else to Do It.............................................................................36 Summary....................................................................................................................36 v 3006_Ch00_CMP2 12/14/03 8:56 AM Page v Chapter 2 Getting Started with Apache.................................37 Installing Apache..............................................................................................38 Getting Apache..................................................................................................38 Installing Apache from Binary Distribution....................................................39 Installing Apache from Source.........................................................................41 Installing Apache from Prebuilt Packages.......................................................41 Installing Apache by Hand...............................................................................45 Upgrading Apache.............................................................................................47 Other Issues.......................................................................................................49 Basic Configuration..........................................................................................50 Decisions............................................................................................................50 Introducing the Master Configuration File.....................................................55 Other Basic Configuration Directives..............................................................56 Starting, Stopping, and Restarting the Server.................................57 Starting Apache on Unix...................................................................................58 Starting Apache on Windows...........................................................................59 Invocation Options...........................................................................................60 Restarting the Server.........................................................................................73 Stopping the Server...........................................................................................75 Starting the Server Automatically....................................................................76 Testing the Server............................................................................................81 Testing with a Browser......................................................................................82 Testing from the Command Line or a Terminal Program..............................82 Testing the Server Configuration Without Starting It.....................................85 Getting the Server Status from the Command Line.......................................86 Using Graphical Configuration Tools.......................................................86 Comanche..........................................................................................................87 TkApache...........................................................................................................91 LinuxConf..........................................................................................................91 Webmin..............................................................................................................91 ApacheConf.......................................................................................................97 Other Configuration Tools................................................................................99 Summary..................................................................................................................100 Chapter 3 Building Apache the Way You Want It...........101 Why Build Apache Yourself?.........................................................................101 Verifying the Apache Source Archive.............................................................103 Building Apache from Source......................................................................105 Configuring and Building Apache.................................................................106 Determining Which Modules to Include.......................................................111 Building Apache As a Dynamic Server..........................................................116 Contents vi 3006_Ch00_CMP2 12/14/03 8:56 AM Page vi Changing the Module Order (Apache 1.3)....................................................118 Checking the Generated Configuration........................................................120 Building Apache from Source As an RPM (Apache 2)..................................122 Advanced Configuration.................................................................................124 Configuring Apache’s Layout..........................................................................124 Choosing a Layout Scheme............................................................................124 Choosing a Multiprocessing Module (Apache 2)..........................................132 Rules (Apache 1.3)...........................................................................................135 Building Apache with suExec support...........................................................137 Configuring Apache’s Supporting Files and Scripts.....................................139 Configuring Apache 2 for Cross-Platform Builds.........................................140 Configuring Apache for Production or Debug Builds..................................142 Configuring Apache for Binary Distribution.................................................143 Configuring Apache’s Library and Include Paths..........................................143 Configuring the Build Environment.........................................................144 Building Modules with configure and apxs..........................................146 Adding Third-Party Modules with configure................................................146 Building Modules with apxs...........................................................................148 Installing Modules with apxs..........................................................................150 Generating Module Templates with apxs......................................................151 Overriding apxs Defaults and Using apxs in makefiles................................152 Summary..................................................................................................................153 Chapter 4 Configuring Apache the Way You Want It...155 Where Apache Looks for Its Configuration..........................................155 Configuration File Syntax...............................................................................156 Configuration for Virtual Hosts......................................................................156 Including Multiple Configuration Files.........................................................157 Per-Directory Configuration..........................................................................159 Conditional Configuration.............................................................................160 How Apache Structures Its Configuration............................................163 Apache’s Container Directives........................................................................164 Directive Types and Locations.......................................................................168 Where Directives Can Go................................................................................171 Container Scope and Nesting.........................................................................172 How Apache Combines Containers and Their Contents.............................174 Legality of Directives in Containers...............................................................175 Options and Overrides....................................................................................176 Enabling and Disabling Features with Options............................................176 Overriding Directives with Per-Directory Configuration.............................179 Contents vii 3006_Ch00_CMP2 12/14/03 8:56 AM Page vii Restricting Access with allow and deny..............................................182 Controlling Access by Name...........................................................................183 Controlling Access by IP Address...................................................................184 Controlling Subnet Access by Network and Netmask..................................185 Controlling Access by HTTP Header.............................................................186 Combining Host-Based Access with User Authentication...........................187 Overriding Host-Based Access.......................................................................188 Directory Listings..........................................................................................188 Enabling and Disabling Directory Indices....................................................189 How mod_autoindex Generates the HTML Page.........................................190 Controlling Which Files Are Seen with IndexIgnore.....................................196 Controlling the Sort Order..............................................................................197 Assigning Icons................................................................................................199 Assigning Descriptions...................................................................................202 Apache’s Environment......................................................................................203 Setting, Unsetting, and Passing Variables from the Shell.............................204 Setting Variables Conditionally......................................................................205 Special Browser Variables...............................................................................207 Detecting Robots with BrowserMatch...........................................................209 Passing Variables to CGI.................................................................................209 Conditional Access Control............................................................................210 Caveats with SetEnvIf vs. SetEnv....................................................................210 Setting Variables with mod_rewrite...............................................................211 Controlling Request and Response Headers..........................................211 Setting Custom Response Headers................................................................213 Setting Custom Request Headers...................................................................215 Inserting Dynamic Values into Headers........................................................216 Setting Custom Headers Conditionally.........................................................217 Retrieving Response Headers from Metadata Files......................................217 Setting Expiry Times.......................................................................................219 Sending Content As-Is....................................................................................222 Controlling the Server Identification Header.................................223 Sending a Content Digest.............................................................................224 Handling the Neighbors.................................................................................225 Controlling Robots with robots.txt................................................................226 Controlling Robots in HTML..........................................................................227 Controlling Robots with Access Control........................................................227 Attracting Robots.............................................................................................228 Making Sure Robots Index the Right Information........................................228 Known Robots, Bad Robots, and Further Reading.......................................229 Summary..................................................................................................................229 Contents viii 3006_Ch00_CMP2 12/14/03 8:56 AM Page viii Chapter 5 Deciding What the Client Needs........................231 Content Handling and Negotiation...........................................................231 File Types.........................................................................................................232 File Encoding...................................................................................................236 File Languages.................................................................................................243 File Character Sets...........................................................................................245 Handling URLs with Extra Path Information................................................247 Content Negotiation.......................................................................................248 Content Negotiation with MultiViews...........................................................250 File Permutations and Valid URLs with MultiViews.....................................256 Magic MIME Types..........................................................................................260 Error and Response Handling......................................................................264 How Apache Handles Errors...........................................................................265 Error and Response Codes.............................................................................265 The ErrorDocument Directive.......................................................................266 Limitations of ErrorDocument......................................................................270 Aliases and Redirection...............................................................................271 Aliases and Script Aliases................................................................................271 Redirections.....................................................................................................273 Rewriting URLs with mod_rewrite.................................................................277 Server-Side Image Maps.................................................................................300 Matching Misspelled URLS............................................................................305 Summary..................................................................................................................306 Chapter 6 Delivering Dynamic Content..................................307 Server-Side Includes......................................................................................308 Enabling SSI.....................................................................................................309 Format of SSI Commands...............................................................................311 The SSI Command Set....................................................................................312 SSI Variables.....................................................................................................312 Passing Trailing Path Information to SSIs (and Other Dynamic Documents).................................................................315 Setting the Date and Error Format.................................................................316 Templating with SSIs.......................................................................................317 Caching Server-Parsed Documents...............................................................319 Identifying Server-Parsed Documents by Execute Permission...................320 CGI: The Common Gateway Interface.........................................................321 CGI and the Environment..............................................................................321 Configuring Apache to Recognize CGI Scripts.............................................323 Setting Up a CGI Directory with ExecCGI: A Simple Way............................327 Triggering CGI Scripts on Events...................................................................330 Contents ix 3006_Ch00_CMP2 12/14/03 8:56 AM Page ix ISINDEX-Style CGI Scripts and Command Line Arguments................332 Writing and Debugging CGI Scripts.........................................................333 A Minimal CGI Script......................................................................................333 Interactive Scripts: A Simple Form................................................................337 Adding Headers...............................................................................................338 Debugging CGI Scripts....................................................................................339 Setting the CGI Daemon Socket.....................................................................345 Limiting CGI Resource Usage.........................................................................346 Actions, Handlers, and Filters................................................................347 Handlers...........................................................................................................348 Filters................................................................................................................354 Dynamic Content and Security....................................................................363 CGI Security Issues..........................................................................................363 Security Advice on the Web............................................................................364 Security Issues with Apache CGI Configuration...........................................364 An Example of an Insecure CGI Script..........................................................365 Known Insecure CGI Scripts...........................................................................370 CGI Wrappers...................................................................................................370 Security Checklist............................................................................................380 Inventing a Better CGI Script with FastCGI......................................381 Summary..................................................................................................................403 Chapter 7 Hosting More Than One Web Site........................405 Implementing User Directories with UserDir......................................406 Enabling and Disabling Specific Users..........................................................407 Redirecting Users to Other Servers................................................................408 Alternative Ways to Implement User Directories.........................................409 Separate Servers..............................................................................................410 Restricting Apache’s Field of View..................................................................411 Specifying Different Configurations and Server Roots................................412 Starting Separate Servers from the Same Configuration.............................412 Sharing External Configuration Files.............................................................413 IP-Based Virtual Hosting.............................................................................414 Multiple IPs, Separate Networks, and Virtual Interfaces..............................415 Configuring What Apache Listens To.............................................................416 Defining IP-Based Virtual Hosts.....................................................................418 Virtual Hosts and the Server-Level Configuration........................................421 Specifying Virtual Host User Privileges..........................................................422 Excluded Directives.........................................................................................426 Default Virtual Hosts....................................................................................427 Contents x 3006_Ch00_CMP2 12/14/03 8:56 AM Page x Name-Based Virtual Hosting.........................................................................428 Defining Named Virtual Hosts.......................................................................428 Server Names and Aliases...............................................................................430 Defining a Default Host for Name-Based Virtual Hosting...........................430 Mixing IP-Based and Name-Based Hosting..................................................431 Issues Affecting Virtual Hosting...........................................................434 Log Files and File Handles..............................................................................434 Virtual Hosts and Server Security..................................................................436 Secure HTTP and Virtual Hosts......................................................................437 Handling HTTP/1.0 Clients with Name-Based Virtual Hosts......................439 Dynamic Virtual Hosting...............................................................................441 Mass Hosting with Virtual-Host Aliases........................................................441 Mapping Hostnames Dynamically with mod_rewrite.................................448 Generating On the Fly and Included Configuration Files with mod_perl..449 Summary..................................................................................................................455 Chapter 8 Improving Apache’s Performance........................457 Apache’s Performance Directives..............................................................458 Configuring MPMs: Processes and Threads..................................................459 Network and IP-Related Performance Directives.........................................470 HTTP-Related Performance Directives.........................................................472 HTTP Limit Directives....................................................................................475 Configuring Apache for Better Performance........................................477 Directives That Affect Performance...............................................................477 Additional Directives for Tuning Performance.............................................482 Benchmarking Apache’s Performance.........................................................490 Benchmarking Apache with ab......................................................................490 Benchmarking Apache with gprof.................................................................495 External Benchmarking Tools........................................................................496 Benchmarking Strategy and Pitfalls...............................................................496 A Performance Checklist...............................................................................497 Proxying................................................................................................................498 Installing and Enabling Proxy Services..........................................................498 Normal Proxy Operation.................................................................................499 Configuring Apache As a Proxy......................................................................500 URL Matching with Directory Containers....................................................502 Blocking Sites via the Proxy............................................................................504 Localizing Remote URLs and Hiding Servers from View.............................504 Relaying Requests to Remote Proxies............................................................508 Proxy Chains and the Via Header...................................................................509 Proxies and Intranets......................................................................................512 Handling Errors...............................................................................................512 Contents xi 3006_Ch00_CMP2 12/14/03 8:56 AM Page xi Timing Out Proxy Requests............................................................................514 Tunneling Other Protocols.............................................................................514 Tuning Proxy Operations................................................................................515 Squid: A High-Performance Proxy Alternative.............................................516 Caching..................................................................................................................516 Enabling Caching............................................................................................516 File-Based Caching.........................................................................................517 In-Memory Caching (Apache 2 Only)............................................................520 Coordinating Memory-Based and Disk-Based Caches................................522 General Cache Configuration.........................................................................522 Maintaining Good Relations with External Caches......................................527 Fault Tolerance and Clustering................................................................529 Backup Server via Redirected Secondary DNS.............................................530 Load Sharing with Round-Robin DNS...........................................................531 Backup Server via Floating IP Address..........................................................531 Hardware Load Balancing..............................................................................532 Clustering with Apache...................................................................................533 Other Clustering Solutions.............................................................................536 Summary..................................................................................................................537 Chapter 9 Monitoring Apache.........................................................539 Logs and Logging..............................................................................................539 Log Files and Security.....................................................................................540 The Error Log...................................................................................................540 Setting the Log Level.......................................................................................541 Logging Errors to the System Log..................................................................542 Transfer Logs...................................................................................................544 Driving Applications Through Logs...............................................................554 Log Rotation....................................................................................................556 Lies, Logs, and Statistics.........................................................................560 What You Can’t Find Out from Logs...............................................................560 Analog: A Log Analyzer...................................................................................561 Server Information..........................................................................................577 Server Status....................................................................................................578 Server Info........................................................................................................581 Securing Access to Server Information.........................................................582 User Tracking.....................................................................................................583 Alternatives to User Tracking.........................................................................584 Cookie Tracking with mod_usertrack............................................................584 URL Tracking with mod_session....................................................................589 Other Session Tracking Options.....................................................................594 Summary..................................................................................................................595 Contents xii 3006_Ch00_CMP2 12/14/03 8:56 AM Page xii Chapter 10Securing Apache..............................................................597 User Authentication........................................................................................597 Apache Authentication Modules...................................................................598 Authentication Configuration Requirements...............................................599 Using Authentication Directives in .htaccess...............................................601 Basic Authentication.......................................................................................601 Digest Authentication.....................................................................................603 Anonymous Authentication...........................................................................606 Setting Up User Information..........................................................................606 Specifying User Requirements.......................................................................614 LDAP Authentication......................................................................................617 Using Multiple Authentication Schemes.......................................................624 Combining User- and Host-Based Authentication......................................626 Securing Basic Authentication with SSL.......................................................627 SSL and Apache...................................................................................................627 Downloading OpenSSL and ModSSL............................................................628 Building and Installing the OpenSSL Library...............................................629 Building and Installing mod_ssl for Apache 2..............................................633 Building and Installing mod_ssl for Apache 1.3...........................................633 Basic SSL Configuration.................................................................................637 Installing a Private Key....................................................................................639 Creating a Certificate Signing Request and Temporary Certificate.............640 Getting a Signed Certificate............................................................................642 Advanced SSL Configuration.........................................................................644 Server-Level Configuration............................................................................644 Client Certification..........................................................................................657 Using Client Certification with User Authentication..................659 SSL and Logging..............................................................................................660 SSL Environment Variables and CGI.............................................................662 SSL and Virtual Hosts......................................................................................666 Advanced Features..........................................................................................668 Summary..................................................................................................................671 Chapter 11Improving Web Server Security..........................673 Apache Features.................................................................................................673 Unwanted Files................................................................................................674 Automatic Directory Indices..........................................................................674 Symbolic Links................................................................................................675 Server-Side Includes.......................................................................................676 ISINDEX-Style CGI Scripts.............................................................................677 Server Tokens...................................................................................................677 Contents xiii 3006_Ch00_CMP2 12/14/03 8:56 AM Page xiii File Permissions..............................................................................................678 Viewing Server Information with mod_info..........................................679 Restricting Server Privileges..................................................................679 Restricting Access by Hostname and IP Address...............................680 Other Server Security Measures................................................................682 Dedicated Server..............................................................................................682 File Integrity...................................................................................................683 md5sum...........................................................................................................684 Tripwire............................................................................................................685 Hardening the Server......................................................................................686 Minimizing Services........................................................................................686 Port Scanning with nmap ..............................................................................688 Probing with Nessus.......................................................................................689 Hardening Windows 2000 and XP..................................................................689 Disabling Network Services.........................................................................690 File Transfer Protocol (FTP)............................................................................690 telnet................................................................................................................690 rlogin, rsh, rexec, rcp.......................................................................................690 Network Filesystem (NFS)..............................................................................690 sendmail/Other Mail Transport Agents (MTAs)...........................................691 Restricting Services with TCP Wrappers........................................................691 Security Fixes, Alerts, and Online Resources.................................693 The WWW Security FAQ..................................................................................693 The BugTraQ Mailing List and Archive..........................................................693 Operating System Newsletters.......................................................................693 Package and Module Notification..................................................................694 Removing Important Data from the Server............................................694 Enabling Secure Logins with SSH..............................................................694 Building and Installing OpenSSH..................................................................695 Authentication Strategies...............................................................................698 Configuring SSH..............................................................................................699 Testing SSH......................................................................................................702 Expanding SSH to Authenticate Users..........................................................703 Secure Server Backups with Rsync and SSH.................................................704 Forwarding Client Connections to Server Applications...............................705 Firewalls and Multifacing Servers.........................................................706 Types of Firewall..............................................................................................706 Designing the Network Topology...................................................................707 Running Apache Under a Virtual chroot Root Directory................709 What chroot Is.................................................................................................709 What chroot Isn’t.............................................................................................710 Setting Up Apache for chroot Operation.......................................................711 Contents xiv 3006_Ch00_CMP2 12/14/03 8:56 AM Page xiv Server Security Checklist...........................................................................723 Avoid Root Services.........................................................................................723 Maintain Logs Properly..................................................................................723 Keep It Simple..................................................................................................724 Block Abusive Clients......................................................................................724 Have an Effective Backup and Restore Process............................................725 Plan for High Availability, Capacity, and Disaster Recovery........................725 Monitor the Server..........................................................................................725 Take Care with Information Flow...................................................................726 Choose an Effective robots.txt Policy............................................................726 Summary..................................................................................................................726 Chapter 12Extending Apache............................................................727 WebDAV....................................................................................................................727 Adding WebDAV to Apache.............................................................................728 The WebDAV Protocol.....................................................................................729 Configuring Apache for WebDAV...................................................................731 Restricting Options and Disabling Overrides...............................................734 WebDAV and Virtual Hosts.............................................................................735 Configuring the DAV Lock Time.....................................................................735 Limitations of File-Based Repositories..........................................................736 Protecting WebDAV Servers............................................................................737 More Advanced Configurations.....................................................................737 Cooperating with CGI and Other Content Handlers....................................740 ISAPI......................................................................................................................741 Supported ISAPI Support Functions.............................................................742 Configuring ISAPI Extensions........................................................................743 Setting the Maximum Initial Request Data Size...........................................744 Logging ISAPI Extensions...............................................................................745 Preloading and Caching ISAPI Extensions....................................................746 Handling Asynchronous ISAPI Extensions...................................................746 Perl.........................................................................................................................746 Building and Installing mod_perl..................................................................748 Migrating mod_perl from Apache 1.3 to Apache 2.......................................755 Configuring and Implementing Perl Handlers.............................................758 Configuring and Implementing Perl Filters..................................................771 Warnings, Taint Mode, and Debugging.........................................................772 Managing Perl Threads in mod_perl 2...........................................................774 Initializing Modules at Startup.......................................................................779 Restarting mod_perl and Auto-Reloading Modules.....................................780 Creating a mod_perl Status Page...................................................................782 Running CGI Scripts Under mod_perl..........................................................782 Contents xv 3006_Ch00_CMP2 12/14/03 8:56 AM Page xv CGI Caveats......................................................................................................785 Passing Variables to Perl Handlers.................................................................787 Using mod_perl with Server-Side Includes...................................................788 Embedding Perl in HTML...............................................................................789 Embedding Perl in Apache’s Configuration..................................................794 PHP...........................................................................................................................795 Installing PHP..................................................................................................796 Getting the PHP source...................................................................................796 Configuring Apache to Work with PHP..........................................................802 Configuring PHP.............................................................................................803 Testing PHP with Apache................................................................................807 Tomcat/Java.........................................................................................................807 So What Is Tomcat?..........................................................................................807 Installation.......................................................................................................808 Tomcat Configuration.....................................................................................813 mod_jk.............................................................................................................818 Mod_python....................................................................................................829 mod_ruby.........................................................................................................835 Summary..................................................................................................................839 Index....................................................................................................................843

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值