code
stringlengths 11
335k
| docstring
stringlengths 20
11.8k
| func_name
stringlengths 1
100
| language
stringclasses 1
value | repo
stringclasses 245
values | path
stringlengths 4
144
| url
stringlengths 43
214
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func (bucket Bucket) DoPostSelectObject(key string, params map[string]interface{}, buf *bytes.Buffer, options ...Option) (*SelectObjectResponse, error) {
resp, err := bucket.do("POST", key, params, options, buf, nil)
if err != nil {
return nil, err
}
result := &SelectObjectResponse{
Body: resp.Body,
StatusCode: resp.StatusCode,
Frame: SelectObjectResult{},
}
result.Headers = resp.Headers
// result.Frame = SelectObjectResult{}
result.ReadTimeOut = bucket.GetConfig().Timeout
// Progress
listener := GetProgressListener(options)
// CRC32
crcCalc := crc32.NewIEEE()
result.WriterForCheckCrc32 = crcCalc
result.Body = TeeReader(resp.Body, nil, 0, listener, nil)
err = CheckRespCode(resp.StatusCode, []int{http.StatusPartialContent, http.StatusOK})
return result, err
} | DoPostSelectObject is the SelectObject/CreateMeta api, approve csv and json file.
key the object key.
params the resource of oss approve csv/meta, json/meta, csv/select, json/select.
buf the request data trans to buffer.
options the options for select file of the object.
SelectObjectResponse the response of select object.
error it's nil if no error, otherwise it's an error object. | DoPostSelectObject | go | aliyun/aliyun-oss-go-sdk | oss/select_object.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object.go | MIT |
func (bucket Bucket) SelectObjectIntoFile(key, fileName string, selectReq SelectRequest, options ...Option) error {
tempFilePath := fileName + TempFileSuffix
params := map[string]interface{}{}
if selectReq.InputSerializationSelect.JsonBodyInput.JsonIsEmpty() {
params["x-oss-process"] = "csv/select" // default select csv file
} else {
params["x-oss-process"] = "json/select"
}
selectReq.encodeBase64()
bs, err := xml.Marshal(selectReq)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
resp, err := bucket.DoPostSelectObject(key, params, buffer, options...)
if err != nil {
return err
}
defer resp.Close()
// If the local file does not exist, create a new one. If it exists, overwrite it.
fd, err := os.OpenFile(tempFilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, FilePermMode)
if err != nil {
return err
}
// Copy the data to the local file path.
_, err = io.Copy(fd, resp)
fd.Close()
if err != nil {
return err
}
return os.Rename(tempFilePath, fileName)
} | SelectObjectIntoFile is the selectObject to file api
key the object key.
fileName saving file's name to localstation.
selectReq the request data for select object
options the options for select file of the object.
error it's nil if no error, otherwise it's an error object. | SelectObjectIntoFile | go | aliyun/aliyun-oss-go-sdk | oss/select_object.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object.go | MIT |
func disableHTTPRedirect(client *http.Client) {
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
} | http.ErrUseLastResponse only is defined go1.7 onward | disableHTTPRedirect | go | aliyun/aliyun-oss-go-sdk | oss/redirect_1_7.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/redirect_1_7.go | MIT |
func (cs *OssCredentialBucketSuite) SetUpSuite(c *C) {
if credentialUID == "" {
testLogger.Println("the cerdential UID is NULL, skip the credential test")
c.Skip("the credential Uid is null")
}
cs.credentialSubUser(c)
client, err := New(endpoint, credentialAccessID, credentialAccessKey)
c.Assert(err, IsNil)
cs.creClient = client
bucket, err := cs.creClient.Bucket(credentialBucketName)
c.Assert(err, IsNil)
cs.creBucket = bucket
testLogger.Println("test credetial bucket started")
} | SetUpSuite runs once when the suite starts running. | SetUpSuite | go | aliyun/aliyun-oss-go-sdk | oss/bucket_credential_test.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket_credential_test.go | MIT |
func (bucket CryptoBucket) CopyFile(srcBucketName, srcObjectKey, destObjectKey string, partSize int64, options ...oss.Option) error {
return fmt.Errorf("CryptoBucket doesn't support CopyFile")
} | CopyFile with multi part mode, temporarily not supported | CopyFile | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_multicopy.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_multicopy.go | MIT |
func (pcc PartCryptoContext) Valid() bool {
if pcc.ContentCipher == nil || pcc.DataSize == 0 || pcc.PartSize == 0 {
return false
}
return true
} | Valid judge PartCryptoContext is valid or not | Valid | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_multipart.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_multipart.go | MIT |
func (bucket CryptoBucket) InitiateMultipartUpload(objectKey string, cryptoContext *PartCryptoContext, options ...oss.Option) (oss.InitiateMultipartUploadResult, error) {
options = bucket.AddEncryptionUaSuffix(options)
var imur oss.InitiateMultipartUploadResult
if cryptoContext == nil {
return imur, fmt.Errorf("error,cryptoContext is nil")
}
if cryptoContext.PartSize <= 0 {
return imur, fmt.Errorf("invalid PartCryptoContext's PartSize %d", cryptoContext.PartSize)
}
cc, err := bucket.ContentCipherBuilder.ContentCipher()
if err != nil {
return imur, err
}
if cryptoContext.PartSize%int64(cc.GetAlignLen()) != 0 {
return imur, fmt.Errorf("PartCryptoContext's PartSize must be aligned to %d", cc.GetAlignLen())
}
opts := addCryptoHeaders(options, cc.GetCipherData())
if cryptoContext.DataSize > 0 {
opts = append(opts, oss.Meta(OssClientSideEncryptionDataSize, strconv.FormatInt(cryptoContext.DataSize, 10)))
}
opts = append(opts, oss.Meta(OssClientSideEncryptionPartSize, strconv.FormatInt(cryptoContext.PartSize, 10)))
imur, err = bucket.Bucket.InitiateMultipartUpload(objectKey, opts...)
if err == nil {
cryptoContext.ContentCipher = cc
}
return imur, err
} | InitiateMultipartUpload initializes multipart upload for client encryption
cryptoContext.PartSize and cryptoContext.DataSize are input parameter
cryptoContext.PartSize must aligned to the secret iv length
cryptoContext.ContentCipher is output parameter
cryptoContext will be used in next API | InitiateMultipartUpload | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_multipart.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_multipart.go | MIT |
func (bucket CryptoBucket) UploadPart(imur oss.InitiateMultipartUploadResult, reader io.Reader,
partSize int64, partNumber int, cryptoContext PartCryptoContext, options ...oss.Option) (oss.UploadPart, error) {
options = bucket.AddEncryptionUaSuffix(options)
var uploadPart oss.UploadPart
if cryptoContext.ContentCipher == nil {
return uploadPart, fmt.Errorf("error,cryptoContext is nil or cryptoContext.ContentCipher is nil")
}
if partNumber < 1 {
return uploadPart, fmt.Errorf("partNumber:%d is smaller than 1", partNumber)
}
if cryptoContext.PartSize%int64(cryptoContext.ContentCipher.GetAlignLen()) != 0 {
return uploadPart, fmt.Errorf("PartCryptoContext's PartSize must be aligned to %d", cryptoContext.ContentCipher.GetAlignLen())
}
cipherData := cryptoContext.ContentCipher.GetCipherData().Clone()
// caclulate iv based on part number
if partNumber > 1 {
cipherData.SeekIV(uint64(partNumber-1) * uint64(cryptoContext.PartSize))
}
// for parallel upload part
partCC, _ := cryptoContext.ContentCipher.Clone(cipherData)
cryptoReader, err := partCC.EncryptContent(reader)
if err != nil {
return uploadPart, err
}
request := &oss.UploadPartRequest{
InitResult: &imur,
Reader: cryptoReader,
PartSize: partCC.GetEncryptedLen(partSize),
PartNumber: partNumber,
}
opts := addCryptoHeaders(options, partCC.GetCipherData())
if cryptoContext.DataSize > 0 {
opts = append(opts, oss.Meta(OssClientSideEncryptionDataSize, strconv.FormatInt(cryptoContext.DataSize, 10)))
}
opts = append(opts, oss.Meta(OssClientSideEncryptionPartSize, strconv.FormatInt(cryptoContext.PartSize, 10)))
result, err := bucket.Bucket.DoUploadPart(request, opts)
return result.Part, err
} | UploadPart uploads parts to oss, the part data are encrypted automaticly on client side
cryptoContext is the input parameter | UploadPart | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_multipart.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_multipart.go | MIT |
func (bucket CryptoBucket) UploadPartFromFile(imur oss.InitiateMultipartUploadResult, filePath string,
startPosition, partSize int64, partNumber int, cryptoContext PartCryptoContext, options ...oss.Option) (oss.UploadPart, error) {
options = bucket.AddEncryptionUaSuffix(options)
var uploadPart = oss.UploadPart{}
if cryptoContext.ContentCipher == nil {
return uploadPart, fmt.Errorf("error,cryptoContext is nil or cryptoContext.ContentCipher is nil")
}
if cryptoContext.PartSize%int64(cryptoContext.ContentCipher.GetAlignLen()) != 0 {
return uploadPart, fmt.Errorf("PartCryptoContext's PartSize must be aligned to %d", cryptoContext.ContentCipher.GetAlignLen())
}
fd, err := os.Open(filePath)
if err != nil {
return uploadPart, err
}
defer fd.Close()
fd.Seek(startPosition, os.SEEK_SET)
if partNumber < 1 {
return uploadPart, fmt.Errorf("partNumber:%d is smaller than 1", partNumber)
}
cipherData := cryptoContext.ContentCipher.GetCipherData().Clone()
// calculate iv based on part number
if partNumber > 1 {
cipherData.SeekIV(uint64(partNumber-1) * uint64(cryptoContext.PartSize))
}
// for parallel upload part
partCC, _ := cryptoContext.ContentCipher.Clone(cipherData)
cryptoReader, err := partCC.EncryptContent(fd)
if err != nil {
return uploadPart, err
}
encryptedLen := partCC.GetEncryptedLen(partSize)
opts := addCryptoHeaders(options, partCC.GetCipherData())
if cryptoContext.DataSize > 0 {
opts = append(opts, oss.Meta(OssClientSideEncryptionDataSize, strconv.FormatInt(cryptoContext.DataSize, 10)))
}
opts = append(opts, oss.Meta(OssClientSideEncryptionPartSize, strconv.FormatInt(cryptoContext.PartSize, 10)))
request := &oss.UploadPartRequest{
InitResult: &imur,
Reader: cryptoReader,
PartSize: encryptedLen,
PartNumber: partNumber,
}
result, err := bucket.Bucket.DoUploadPart(request, opts)
return result.Part, err
} | UploadPartFromFile uploads part from the file, the part data are encrypted automaticly on client side
cryptoContext is the input parameter | UploadPartFromFile | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_multipart.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_multipart.go | MIT |
func (bucket CryptoBucket) UploadPartCopy(imur oss.InitiateMultipartUploadResult, srcBucketName, srcObjectKey string,
startPosition, partSize int64, partNumber int, cryptoContext PartCryptoContext, options ...oss.Option) (oss.UploadPart, error) {
var uploadPart = oss.UploadPart{}
return uploadPart, fmt.Errorf("CryptoBucket doesn't support UploadPartCopy")
} | UploadPartCopy uploads part copy | UploadPartCopy | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_multipart.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_multipart.go | MIT |
func (bucket CryptoBucket) UploadFile(objectKey, filePath string, partSize int64, options ...oss.Option) error {
return fmt.Errorf("CryptoBucket doesn't support UploadFile")
} | UploadFile with multi part mode | UploadFile | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_upload.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_upload.go | MIT |
func (rc *CryptoEncrypter) Close() error {
rc.isClosed = true
if closer, ok := rc.Body.(io.ReadCloser); ok {
return closer.Close()
}
return nil
} | Close lets the CryptoEncrypter satisfy io.ReadCloser interface | Close | go | aliyun/aliyun-oss-go-sdk | oss/crypto/cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/cipher.go | MIT |
func (rc *CryptoEncrypter) Read(b []byte) (int, error) {
if rc.isClosed {
return 0, io.EOF
}
return rc.Encrypter.Read(b)
} | Read lets the CryptoEncrypter satisfy io.ReadCloser interface | Read | go | aliyun/aliyun-oss-go-sdk | oss/crypto/cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/cipher.go | MIT |
func (rc *CryptoDecrypter) Close() error {
rc.isClosed = true
if closer, ok := rc.Body.(io.ReadCloser); ok {
return closer.Close()
}
return nil
} | Close lets the CryptoDecrypter satisfy io.ReadCloser interface | Close | go | aliyun/aliyun-oss-go-sdk | oss/crypto/cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/cipher.go | MIT |
func (rc *CryptoDecrypter) Read(b []byte) (int, error) {
if rc.isClosed {
return 0, io.EOF
}
return rc.Decrypter.Read(b)
} | Read lets the CryptoDecrypter satisfy io.ReadCloser interface | Read | go | aliyun/aliyun-oss-go-sdk | oss/crypto/cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/cipher.go | MIT |
func (s *OssCryptoBucketSuite) SetUpSuite(c *C) {
} | SetUpSuite runs once when the suite starts running | SetUpSuite | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket_test.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket_test.go | MIT |
func (s *OssCryptoBucketSuite) TearDownSuite(c *C) {
} | TearDownSuite runs before each test or benchmark starts running | TearDownSuite | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket_test.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket_test.go | MIT |
func (s *OssCryptoBucketSuite) SetUpTest(c *C) {
} | SetUpTest runs after each test or benchmark runs | SetUpTest | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket_test.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket_test.go | MIT |
func (s *OssCryptoBucketSuite) TearDownTest(c *C) {
} | TearDownTest runs once after all tests or benchmarks have finished running | TearDownTest | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket_test.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket_test.go | MIT |
func CreateAesCtrCipher(cipher MasterCipher) ContentCipherBuilder {
return aesCtrCipherBuilder{MasterCipher: cipher}
} | CreateAesCtrCipher creates ContentCipherBuilder | CreateAesCtrCipher | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (builder aesCtrCipherBuilder) createCipherData() (CipherData, error) {
var cd CipherData
var err error
err = cd.RandomKeyIv(aesKeySize, ivSize)
if err != nil {
return cd, err
}
cd.WrapAlgorithm = builder.MasterCipher.GetWrapAlgorithm()
cd.CEKAlgorithm = AesCtrAlgorithm
cd.MatDesc = builder.MasterCipher.GetMatDesc()
// EncryptedKey
cd.EncryptedKey, err = builder.MasterCipher.Encrypt(cd.Key)
if err != nil {
return cd, err
}
// EncryptedIV
cd.EncryptedIV, err = builder.MasterCipher.Encrypt(cd.IV)
if err != nil {
return cd, err
}
return cd, nil
} | createCipherData create CipherData for encrypt object data | createCipherData | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (builder aesCtrCipherBuilder) contentCipherCD(cd CipherData) (ContentCipher, error) {
cipher, err := newAesCtr(cd)
if err != nil {
return nil, err
}
return &aesCtrCipher{
CipherData: cd,
Cipher: cipher,
}, nil
} | contentCipherCD is used to create ContentCipher with CipherData | contentCipherCD | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (builder aesCtrCipherBuilder) ContentCipher() (ContentCipher, error) {
cd, err := builder.createCipherData()
if err != nil {
return nil, err
}
return builder.contentCipherCD(cd)
} | ContentCipher is used to create ContentCipher interface | ContentCipher | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (builder aesCtrCipherBuilder) ContentCipherEnv(envelope Envelope) (ContentCipher, error) {
var cd CipherData
cd.EncryptedKey = make([]byte, len(envelope.CipherKey))
copy(cd.EncryptedKey, []byte(envelope.CipherKey))
plainKey, err := builder.MasterCipher.Decrypt([]byte(envelope.CipherKey))
if err != nil {
return nil, err
}
cd.Key = make([]byte, len(plainKey))
copy(cd.Key, plainKey)
cd.EncryptedIV = make([]byte, len(envelope.IV))
copy(cd.EncryptedIV, []byte(envelope.IV))
plainIV, err := builder.MasterCipher.Decrypt([]byte(envelope.IV))
if err != nil {
return nil, err
}
cd.IV = make([]byte, len(plainIV))
copy(cd.IV, plainIV)
cd.MatDesc = envelope.MatDesc
cd.WrapAlgorithm = envelope.WrapAlg
cd.CEKAlgorithm = envelope.CEKAlg
return builder.contentCipherCD(cd)
} | ContentCipherEnv is used to create a decrption ContentCipher from Envelope | ContentCipherEnv | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (builder aesCtrCipherBuilder) GetMatDesc() string {
return builder.MasterCipher.GetMatDesc()
} | GetMatDesc is used to get MasterCipher's MatDesc | GetMatDesc | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (cc *aesCtrCipher) EncryptContent(src io.Reader) (io.ReadCloser, error) {
reader := cc.Cipher.Encrypt(src)
return &CryptoEncrypter{Body: src, Encrypter: reader}, nil
} | EncryptContents will generate a random key and iv and encrypt the data using ctr | EncryptContent | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (cc *aesCtrCipher) DecryptContent(src io.Reader) (io.ReadCloser, error) {
reader := cc.Cipher.Decrypt(src)
return &CryptoDecrypter{Body: src, Decrypter: reader}, nil
} | DecryptContent is used to decrypt object using ctr | DecryptContent | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (cc *aesCtrCipher) GetCipherData() *CipherData {
return &(cc.CipherData)
} | GetCipherData is used to get cipher data information | GetCipherData | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (cc *aesCtrCipher) GetEncryptedLen(plainTextLen int64) int64 {
// AES CTR encryption mode does not change content length
return plainTextLen
} | GetCipherData returns cipher data | GetEncryptedLen | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (cc *aesCtrCipher) GetAlignLen() int {
return len(cc.CipherData.IV)
} | GetAlignLen is used to get align length | GetAlignLen | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func (cc *aesCtrCipher) Clone(cd CipherData) (ContentCipher, error) {
cipher, err := newAesCtr(cd)
if err != nil {
return nil, err
}
return &aesCtrCipher{
CipherData: cd,
Cipher: cipher,
}, nil
} | Clone is used to create a new aesCtrCipher from itself | Clone | go | aliyun/aliyun-oss-go-sdk | oss/crypto/aes_ctr_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/aes_ctr_cipher.go | MIT |
func SetAliKmsClient(client *kms.Client) CryptoBucketOption {
return func(bucket *CryptoBucket) {
bucket.AliKmsClient = client
}
} | SetAliKmsClient set field AliKmsClient of CryptoBucket
If the objects you need to decrypt are encrypted with ali kms master key,but not with ContentCipherBuilder
you provided, you must provide this interface | SetAliKmsClient | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func SetMasterCipherManager(manager MasterCipherManager) CryptoBucketOption {
return func(bucket *CryptoBucket) {
bucket.MasterCipherManager = manager
}
} | SetMasterCipherManager set field MasterCipherManager of CryptoBucket | SetMasterCipherManager | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func SetExtraCipherBuilder(extraBuilder ExtraCipherBuilder) CryptoBucketOption {
return func(bucket *CryptoBucket) {
bucket.ExtraCipherBuilder = extraBuilder
}
} | SetExtraCipherBuilder set field ExtraCipherBuilder of CryptoBucket | SetExtraCipherBuilder | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (decb *DefaultExtraCipherBuilder) GetDecryptCipher(envelope Envelope, cm MasterCipherManager) (ContentCipher, error) {
if cm == nil {
return nil, fmt.Errorf("DefaultExtraCipherBuilder GetDecryptCipher error,MasterCipherManager is nil")
}
if envelope.CEKAlg != AesCtrAlgorithm {
return nil, fmt.Errorf("DefaultExtraCipherBuilder GetDecryptCipher error,not supported content algorithm %s", envelope.CEKAlg)
}
if envelope.WrapAlg != RsaCryptoWrap && envelope.WrapAlg != KmsAliCryptoWrap {
return nil, fmt.Errorf("DefaultExtraCipherBuilder GetDecryptCipher error,not supported envelope wrap algorithm %s", envelope.WrapAlg)
}
matDesc := make(map[string]string)
if envelope.MatDesc != "" {
err := json.Unmarshal([]byte(envelope.MatDesc), &matDesc)
if err != nil {
return nil, err
}
}
masterKeys, err := cm.GetMasterKey(matDesc)
if err != nil {
return nil, err
}
var contentCipher ContentCipher
if envelope.WrapAlg == RsaCryptoWrap {
// for rsa master key
if len(masterKeys) != 2 {
return nil, fmt.Errorf("rsa keys count must be 2,now is %d", len(masterKeys))
}
rsaCipher, err := CreateMasterRsa(matDesc, masterKeys[0], masterKeys[1])
if err != nil {
return nil, err
}
aesCtrBuilder := CreateAesCtrCipher(rsaCipher)
contentCipher, err = aesCtrBuilder.ContentCipherEnv(envelope)
} else if envelope.WrapAlg == KmsAliCryptoWrap {
// for kms master key
if len(masterKeys) != 1 {
return nil, fmt.Errorf("non-rsa keys count must be 1,now is %d", len(masterKeys))
}
if decb.AliKmsClient == nil {
return nil, fmt.Errorf("aliyun kms client is nil")
}
kmsCipher, err := CreateMasterAliKms(matDesc, masterKeys[0], decb.AliKmsClient)
if err != nil {
return nil, err
}
aesCtrBuilder := CreateAesCtrCipher(kmsCipher)
contentCipher, err = aesCtrBuilder.ContentCipherEnv(envelope)
} else {
// to do
// for master keys which are neither rsa nor kms
}
return contentCipher, err
} | GetDecryptCipher is used to get ContentCipher for decrypt object | GetDecryptCipher | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func GetCryptoBucket(client *oss.Client, bucketName string, builder ContentCipherBuilder,
options ...CryptoBucketOption) (*CryptoBucket, error) {
var cryptoBucket CryptoBucket
cryptoBucket.Client = *client
cryptoBucket.BucketName = bucketName
cryptoBucket.ContentCipherBuilder = builder
for _, option := range options {
option(&cryptoBucket)
}
if cryptoBucket.ExtraCipherBuilder == nil {
cryptoBucket.ExtraCipherBuilder = &DefaultExtraCipherBuilder{AliKmsClient: cryptoBucket.AliKmsClient}
}
return &cryptoBucket, nil
} | GetCryptoBucket create a client encyrption bucket | GetCryptoBucket | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) PutObject(objectKey string, reader io.Reader, options ...oss.Option) error {
options = bucket.AddEncryptionUaSuffix(options)
cc, err := bucket.ContentCipherBuilder.ContentCipher()
if err != nil {
return err
}
cryptoReader, err := cc.EncryptContent(reader)
if err != nil {
return err
}
var request *oss.PutObjectRequest
srcLen, err := oss.GetReaderLen(reader)
if err != nil {
request = &oss.PutObjectRequest{
ObjectKey: objectKey,
Reader: cryptoReader,
}
} else {
encryptedLen := cc.GetEncryptedLen(srcLen)
request = &oss.PutObjectRequest{
ObjectKey: objectKey,
Reader: oss.LimitReadCloser(cryptoReader, encryptedLen),
}
}
opts := addCryptoHeaders(options, cc.GetCipherData())
resp, err := bucket.DoPutObject(request, opts)
if err != nil {
return err
}
defer resp.Body.Close()
return err
} | PutObject creates a new object and encyrpt it on client side when uploading to oss | PutObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) GetObject(objectKey string, options ...oss.Option) (io.ReadCloser, error) {
options = bucket.AddEncryptionUaSuffix(options)
result, err := bucket.DoGetObject(&oss.GetObjectRequest{ObjectKey: objectKey}, options)
if err != nil {
return nil, err
}
return result.Response, nil
} | GetObject downloads the object from oss
If the object is encrypted, sdk decrypt it automaticly | GetObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) GetObjectToFile(objectKey, filePath string, options ...oss.Option) error {
options = bucket.AddEncryptionUaSuffix(options)
tempFilePath := filePath + oss.TempFileSuffix
// Calls the API to actually download the object. Returns the result instance.
result, err := bucket.DoGetObject(&oss.GetObjectRequest{ObjectKey: objectKey}, options)
if err != nil {
return err
}
defer result.Response.Close()
// If the local file does not exist, create a new one. If it exists, overwrite it.
fd, err := os.OpenFile(tempFilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, oss.FilePermMode)
if err != nil {
return err
}
// Copy the data to the local file path.
_, err = io.Copy(fd, result.Response.Body)
fd.Close()
if err != nil {
return err
}
// Compares the CRC value
hasRange, _, _ := oss.IsOptionSet(options, oss.HTTPHeaderRange)
encodeOpt, _ := oss.FindOption(options, oss.HTTPHeaderAcceptEncoding, nil)
acceptEncoding := ""
if encodeOpt != nil {
acceptEncoding = encodeOpt.(string)
}
if bucket.GetConfig().IsEnableCRC && !hasRange && acceptEncoding != "gzip" {
result.Response.ClientCRC = result.ClientCRC.Sum64()
err = oss.CheckCRC(result.Response, "GetObjectToFile")
if err != nil {
os.Remove(tempFilePath)
return err
}
}
return os.Rename(tempFilePath, filePath)
} | GetObjectToFile downloads the object from oss to local file
If the object is encrypted, sdk decrypt it automaticly | GetObjectToFile | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) DoGetObject(request *oss.GetObjectRequest, options []oss.Option) (*oss.GetObjectResult, error) {
options = bucket.AddEncryptionUaSuffix(options)
// first,we must head object
metaInfo, err := bucket.GetObjectDetailedMeta(request.ObjectKey)
if err != nil {
return nil, err
}
isEncryptedObj := isEncryptedObject(metaInfo)
if !isEncryptedObj {
return bucket.Bucket.DoGetObject(request, options)
}
envelope, err := getEnvelopeFromHeader(metaInfo)
if err != nil {
return nil, err
}
if !isValidContentAlg(envelope.CEKAlg) {
return nil, fmt.Errorf("not supported content algorithm %s,object:%s", envelope.CEKAlg, request.ObjectKey)
}
if !envelope.IsValid() {
return nil, fmt.Errorf("getEnvelopeFromHeader error,object:%s", request.ObjectKey)
}
// use ContentCipherBuilder to decrpt object by default
encryptMatDesc := bucket.ContentCipherBuilder.GetMatDesc()
var cc ContentCipher
err = nil
if envelope.MatDesc == encryptMatDesc {
cc, err = bucket.ContentCipherBuilder.ContentCipherEnv(envelope)
} else {
cc, err = bucket.ExtraCipherBuilder.GetDecryptCipher(envelope, bucket.MasterCipherManager)
}
if err != nil {
return nil, fmt.Errorf("%s,object:%s", err.Error(), request.ObjectKey)
}
discardFrontAlignLen := int64(0)
uRange, err := oss.GetRangeConfig(options)
if err != nil {
return nil, err
}
if uRange != nil && uRange.HasStart {
// process range to align key size
adjustStart := adjustRangeStart(uRange.Start, cc)
discardFrontAlignLen = uRange.Start - adjustStart
if discardFrontAlignLen > 0 {
uRange.Start = adjustStart
options = oss.DeleteOption(options, oss.HTTPHeaderRange)
options = append(options, oss.NormalizedRange(oss.GetRangeString(*uRange)))
}
// seek iv
cipherData := cc.GetCipherData().Clone()
cipherData.SeekIV(uint64(adjustStart))
cc, _ = cc.Clone(cipherData)
}
params, _ := oss.GetRawParams(options)
resp, err := bucket.Do("GET", request.ObjectKey, params, options, nil, nil)
if err != nil {
return nil, err
}
result := &oss.GetObjectResult{
Response: resp,
}
// CRC
var crcCalc hash.Hash64
hasRange, _, _ := oss.IsOptionSet(options, oss.HTTPHeaderRange)
if bucket.GetConfig().IsEnableCRC && !hasRange {
crcCalc = crc64.New(oss.CrcTable())
result.ServerCRC = resp.ServerCRC
result.ClientCRC = crcCalc
}
// Progress
listener := oss.GetProgressListener(options)
contentLen, _ := strconv.ParseInt(resp.Headers.Get(oss.HTTPHeaderContentLength), 10, 64)
resp.Body = oss.TeeReader(resp.Body, crcCalc, contentLen, listener, nil)
resp.Body, err = cc.DecryptContent(resp.Body)
if err == nil && discardFrontAlignLen > 0 {
resp.Body = &oss.DiscardReadCloser{
RC: resp.Body,
Discard: int(discardFrontAlignLen)}
}
return result, err
} | DoGetObject is the actual API that gets the encrypted or not encrypted object.
It's the internal function called by other public APIs. | DoGetObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) PutObjectFromFile(objectKey, filePath string, options ...oss.Option) error {
options = bucket.AddEncryptionUaSuffix(options)
fd, err := os.Open(filePath)
if err != nil {
return err
}
defer fd.Close()
opts := oss.AddContentType(options, filePath, objectKey)
cc, err := bucket.ContentCipherBuilder.ContentCipher()
if err != nil {
return err
}
cryptoReader, err := cc.EncryptContent(fd)
if err != nil {
return err
}
var request *oss.PutObjectRequest
srcLen, err := oss.GetReaderLen(fd)
if err != nil {
request = &oss.PutObjectRequest{
ObjectKey: objectKey,
Reader: cryptoReader,
}
} else {
encryptedLen := cc.GetEncryptedLen(srcLen)
request = &oss.PutObjectRequest{
ObjectKey: objectKey,
Reader: oss.LimitReadCloser(cryptoReader, encryptedLen),
}
}
opts = addCryptoHeaders(opts, cc.GetCipherData())
resp, err := bucket.DoPutObject(request, opts)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
} | PutObjectFromFile creates a new object from the local file
the object will be encrypted automaticly on client side when uploaded to oss | PutObjectFromFile | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) AppendObject(objectKey string, reader io.Reader, appendPosition int64, options ...oss.Option) (int64, error) {
return 0, fmt.Errorf("CryptoBucket doesn't support AppendObject")
} | AppendObject please refer to Bucket.AppendObject | AppendObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) DoAppendObject(request *oss.AppendObjectRequest, options []oss.Option) (*oss.AppendObjectResult, error) {
return nil, fmt.Errorf("CryptoBucket doesn't support DoAppendObject")
} | DoAppendObject please refer to Bucket.DoAppendObject | DoAppendObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) PutObjectWithURL(signedURL string, reader io.Reader, options ...oss.Option) error {
return fmt.Errorf("CryptoBucket doesn't support PutObjectWithURL")
} | PutObjectWithURL please refer to Bucket.PutObjectWithURL | PutObjectWithURL | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) PutObjectFromFileWithURL(signedURL, filePath string, options ...oss.Option) error {
return fmt.Errorf("CryptoBucket doesn't support PutObjectFromFileWithURL")
} | PutObjectFromFileWithURL please refer to Bucket.PutObjectFromFileWithURL | PutObjectFromFileWithURL | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) DoPutObjectWithURL(signedURL string, reader io.Reader, options []oss.Option) (*oss.Response, error) {
return nil, fmt.Errorf("CryptoBucket doesn't support DoPutObjectWithURL")
} | DoPutObjectWithURL please refer to Bucket.DoPutObjectWithURL | DoPutObjectWithURL | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) GetObjectWithURL(signedURL string, options ...oss.Option) (io.ReadCloser, error) {
return nil, fmt.Errorf("CryptoBucket doesn't support GetObjectWithURL")
} | GetObjectWithURL please refer to Bucket.GetObjectWithURL | GetObjectWithURL | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) GetObjectToFileWithURL(signedURL, filePath string, options ...oss.Option) error {
return fmt.Errorf("CryptoBucket doesn't support GetObjectToFileWithURL")
} | GetObjectToFileWithURL please refer to Bucket.GetObjectToFileWithURL | GetObjectToFileWithURL | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) DoGetObjectWithURL(signedURL string, options []oss.Option) (*oss.GetObjectResult, error) {
return nil, fmt.Errorf("CryptoBucket doesn't support DoGetObjectWithURL")
} | DoGetObjectWithURL please refer to Bucket.DoGetObjectWithURL | DoGetObjectWithURL | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func (bucket CryptoBucket) ProcessObject(objectKey string, process string, options ...oss.Option) (oss.ProcessObjectResult, error) {
var out oss.ProcessObjectResult
return out, fmt.Errorf("CryptoBucket doesn't support ProcessObject")
} | ProcessObject please refer to Bucket.ProcessObject | ProcessObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func isEncryptedObject(headers http.Header) bool {
encrptedKey := headers.Get(oss.HTTPHeaderOssMetaPrefix + OssClientSideEncryptionKey)
return len(encrptedKey) > 0
} | isEncryptedObject judge the object is encrypted or not | isEncryptedObject | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func addCryptoHeaders(options []oss.Option, cd *CipherData) []oss.Option {
opts := []oss.Option{}
// convert content-md5
md5Option, _ := oss.FindOption(options, oss.HTTPHeaderContentMD5, nil)
if md5Option != nil {
opts = append(opts, oss.Meta(OssClientSideEncryptionUnencryptedContentMD5, md5Option.(string)))
options = oss.DeleteOption(options, oss.HTTPHeaderContentMD5)
}
// convert content-length
lenOption, _ := oss.FindOption(options, oss.HTTPHeaderContentLength, nil)
if lenOption != nil {
opts = append(opts, oss.Meta(OssClientSideEncryptionUnencryptedContentLength, lenOption.(string)))
options = oss.DeleteOption(options, oss.HTTPHeaderContentLength)
}
opts = append(opts, options...)
// matDesc
if cd.MatDesc != "" {
opts = append(opts, oss.Meta(OssClientSideEncryptionMatDesc, cd.MatDesc))
}
// encrypted key
strEncryptedKey := base64.StdEncoding.EncodeToString(cd.EncryptedKey)
opts = append(opts, oss.Meta(OssClientSideEncryptionKey, strEncryptedKey))
// encrypted iv
strEncryptedIV := base64.StdEncoding.EncodeToString(cd.EncryptedIV)
opts = append(opts, oss.Meta(OssClientSideEncryptionStart, strEncryptedIV))
// wrap alg
opts = append(opts, oss.Meta(OssClientSideEncryptionWrapAlg, cd.WrapAlgorithm))
// cek alg
opts = append(opts, oss.Meta(OssClientSideEncryptionCekAlg, cd.CEKAlgorithm))
return opts
} | addCryptoHeaders save Envelope information in oss meta | addCryptoHeaders | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_bucket.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_bucket.go | MIT |
func CreateMasterAliKms(matDesc map[string]string, kmsID string, kmsClient *kms.Client) (MasterCipher, error) {
var masterCipher MasterAliKmsCipher
if kmsID == "" || kmsClient == nil {
return masterCipher, fmt.Errorf("kmsID is empty or kmsClient is nil")
}
var jsonDesc string
if len(matDesc) > 0 {
b, err := json.Marshal(matDesc)
if err != nil {
return masterCipher, err
}
jsonDesc = string(b)
}
masterCipher.MatDesc = jsonDesc
masterCipher.KmsID = kmsID
masterCipher.KmsClient = kmsClient
return masterCipher, nil
} | CreateMasterAliKms Create master key interface implemented by ali kms
matDesc will be converted to json string | CreateMasterAliKms | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_alikms_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_alikms_cipher.go | MIT |
func (mrc MasterAliKmsCipher) GetWrapAlgorithm() string {
return KmsAliCryptoWrap
} | GetWrapAlgorithm get master key wrap algorithm | GetWrapAlgorithm | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_alikms_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_alikms_cipher.go | MIT |
func (mkms MasterAliKmsCipher) GetMatDesc() string {
return mkms.MatDesc
} | GetMatDesc get master key describe | GetMatDesc | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_alikms_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_alikms_cipher.go | MIT |
func (mkms MasterAliKmsCipher) Encrypt(plainData []byte) ([]byte, error) {
// kms Plaintext must be base64 encoded
base64Plain := base64.StdEncoding.EncodeToString(plainData)
request := kms.CreateEncryptRequest()
request.RpcRequest.Scheme = "https"
request.RpcRequest.Method = "POST"
request.RpcRequest.AcceptFormat = "json"
request.KeyId = mkms.KmsID
request.Plaintext = base64Plain
response, err := mkms.KmsClient.Encrypt(request)
if err != nil {
return nil, err
}
return base64.StdEncoding.DecodeString(response.CiphertextBlob)
} | Encrypt encrypt data by ali kms
Mainly used to encrypt object's symmetric secret key and iv | Encrypt | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_alikms_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_alikms_cipher.go | MIT |
func (mkms MasterAliKmsCipher) Decrypt(cryptoData []byte) ([]byte, error) {
base64Crypto := base64.StdEncoding.EncodeToString(cryptoData)
request := kms.CreateDecryptRequest()
request.RpcRequest.Scheme = "https"
request.RpcRequest.Method = "POST"
request.RpcRequest.AcceptFormat = "json"
request.CiphertextBlob = string(base64Crypto)
response, err := mkms.KmsClient.Decrypt(request)
if err != nil {
return nil, err
}
return base64.StdEncoding.DecodeString(response.Plaintext)
} | Decrypt decrypt data by ali kms
Mainly used to decrypt object's symmetric secret key and iv | Decrypt | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_alikms_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_alikms_cipher.go | MIT |
func (bucket CryptoBucket) DownloadFile(objectKey, filePath string, partSize int64, options ...oss.Option) error {
return fmt.Errorf("CryptoBucket doesn't support DownloadFile")
} | DownloadFile with multi part mode, temporarily not supported | DownloadFile | go | aliyun/aliyun-oss-go-sdk | oss/crypto/crypto_download.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/crypto_download.go | MIT |
func CreateMasterRsa(matDesc map[string]string, publicKey string, privateKey string) (MasterCipher, error) {
var masterCipher MasterRsaCipher
var jsonDesc string
if len(matDesc) > 0 {
b, err := json.Marshal(matDesc)
if err != nil {
return masterCipher, err
}
jsonDesc = string(b)
}
masterCipher.MatDesc = jsonDesc
masterCipher.PublicKey = publicKey
masterCipher.PrivateKey = privateKey
return masterCipher, nil
} | CreateMasterRsa Create master key interface implemented by rsa
matDesc will be converted to json string | CreateMasterRsa | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_rsa_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_rsa_cipher.go | MIT |
func (mrc MasterRsaCipher) GetWrapAlgorithm() string {
return RsaCryptoWrap
} | GetWrapAlgorithm get master key wrap algorithm | GetWrapAlgorithm | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_rsa_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_rsa_cipher.go | MIT |
func (mrc MasterRsaCipher) GetMatDesc() string {
return mrc.MatDesc
} | GetMatDesc get master key describe | GetMatDesc | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_rsa_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_rsa_cipher.go | MIT |
func (mrc MasterRsaCipher) Encrypt(plainData []byte) ([]byte, error) {
block, _ := pem.Decode([]byte(mrc.PublicKey))
if block == nil {
return nil, fmt.Errorf("pem.Decode public key error")
}
var pub *rsa.PublicKey
if block.Type == "PUBLIC KEY" {
// pks8 format
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pub = pubInterface.(*rsa.PublicKey)
} else if block.Type == "RSA PUBLIC KEY" {
// pks1 format
pub = &rsa.PublicKey{}
_, err := asn1.Unmarshal(block.Bytes, pub)
if err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("not supported public key,type:%s", block.Type)
}
return rsa.EncryptPKCS1v15(rand.Reader, pub, plainData)
} | Encrypt encrypt data by rsa public key
Mainly used to encrypt object's symmetric secret key and iv | Encrypt | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_rsa_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_rsa_cipher.go | MIT |
func (mrc MasterRsaCipher) Decrypt(cryptoData []byte) ([]byte, error) {
block, _ := pem.Decode([]byte(mrc.PrivateKey))
if block == nil {
return nil, fmt.Errorf("pem.Decode private key error")
}
if block.Type == "PRIVATE KEY" {
// pks8 format
privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(rand.Reader, privInterface.(*rsa.PrivateKey), cryptoData)
} else if block.Type == "RSA PRIVATE KEY" {
// pks1 format
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(rand.Reader, priv, cryptoData)
} else {
return nil, fmt.Errorf("not supported private key,type:%s", block.Type)
}
} | Decrypt Decrypt data by rsa private key
Mainly used to decrypt object's symmetric secret key and iv | Decrypt | go | aliyun/aliyun-oss-go-sdk | oss/crypto/master_rsa_cipher.go | https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crypto/master_rsa_cipher.go | MIT |
func NoArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
if cmd.HasSubCommands() {
return errors.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n"))
}
return errors.Errorf(
"\"%s\" accepts no argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s",
cmd.CommandPath(),
cmd.CommandPath(),
cmd.UseLine(),
cmd.Short,
)
} | NoArgs validates args and returns an error if there are any args | NoArgs | go | balena-os/balena-engine | cli/required.go | https://github.com/balena-os/balena-engine/blob/master/cli/required.go | Apache-2.0 |
func SetupRootCommand(rootCmd *cobra.Command) {
cobra.AddTemplateFunc("hasSubCommands", hasSubCommands)
cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands)
cobra.AddTemplateFunc("operationSubCommands", operationSubCommands)
cobra.AddTemplateFunc("managementSubCommands", managementSubCommands)
cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
rootCmd.SetUsageTemplate(usageTemplate)
rootCmd.SetHelpTemplate(helpTemplate)
rootCmd.SetFlagErrorFunc(FlagErrorFunc)
rootCmd.SetVersionTemplate("Docker version {{.Version}}\n")
rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
} | SetupRootCommand sets default usage, help, and error handling for the
root command. | SetupRootCommand | go | balena-os/balena-engine | cli/cobra.go | https://github.com/balena-os/balena-engine/blob/master/cli/cobra.go | Apache-2.0 |
func FlagErrorFunc(cmd *cobra.Command, err error) error {
if err == nil {
return nil
}
usage := ""
if cmd.HasSubCommands() {
usage = "\n\n" + cmd.UsageString()
}
return StatusError{
Status: fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage),
StatusCode: 125,
}
} | FlagErrorFunc prints an error message which matches the format of the
docker/docker/cli error messages | FlagErrorFunc | go | balena-os/balena-engine | cli/cobra.go | https://github.com/balena-os/balena-engine/blob/master/cli/cobra.go | Apache-2.0 |
func Dir() string {
return configDir
} | Dir returns the path to the configuration directory as specified by the DOCKER_CONFIG environment variable.
If DOCKER_CONFIG is unset, Dir returns ~/.docker .
Dir ignores XDG_CONFIG_HOME (same as the docker client).
TODO: this was copied from cli/config/configfile and should be removed once cmd/dockerd moves | Dir | go | balena-os/balena-engine | cli/config/configdir.go | https://github.com/balena-os/balena-engine/blob/master/cli/config/configdir.go | Apache-2.0 |
func Enable() {
os.Setenv("DEBUG", "1")
logrus.SetLevel(logrus.DebugLevel)
} | Enable sets the DEBUG env var to true
and makes the logger to log at debug level. | Enable | go | balena-os/balena-engine | cli/debug/debug.go | https://github.com/balena-os/balena-engine/blob/master/cli/debug/debug.go | Apache-2.0 |
func Disable() {
os.Setenv("DEBUG", "")
logrus.SetLevel(logrus.InfoLevel)
} | Disable sets the DEBUG env var to false
and makes the logger to log at info level. | Disable | go | balena-os/balena-engine | cli/debug/debug.go | https://github.com/balena-os/balena-engine/blob/master/cli/debug/debug.go | Apache-2.0 |
func IsEnabled() bool {
return os.Getenv("DEBUG") != ""
} | IsEnabled checks whether the debug flag is set or not. | IsEnabled | go | balena-os/balena-engine | cli/debug/debug.go | https://github.com/balena-os/balena-engine/blob/master/cli/debug/debug.go | Apache-2.0 |
func NewClient(ctx context.Context, cli *containerd.Client, stateDir, ns string, b libcontainerdtypes.Backend) (libcontainerdtypes.Client, error) {
return remote.NewClient(ctx, cli, stateDir, ns, b)
} | NewClient creates a new libcontainerd client from a containerd client | NewClient | go | balena-os/balena-engine | libcontainerd/libcontainerd_linux.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/libcontainerd_linux.go | Apache-2.0 |
func NewClient(ctx context.Context, cli *containerd.Client, stateDir, ns string, b libcontainerdtypes.Backend) (libcontainerdtypes.Client, error) {
if !system.ContainerdRuntimeSupported() {
return local.NewClient(ctx, cli, stateDir, ns, b)
}
return remote.NewClient(ctx, cli, stateDir, ns, b)
} | NewClient creates a new libcontainerd client from a containerd client | NewClient | go | balena-os/balena-engine | libcontainerd/libcontainerd_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/libcontainerd_windows.go | Apache-2.0 |
func InterfaceToStats(read time.Time, v interface{}) *Stats {
return &Stats{
HCSStats: v.(*hcsshim.Statistics),
Read: read,
}
} | InterfaceToStats returns a stats object from the platform-specific interface. | InterfaceToStats | go | balena-os/balena-engine | libcontainerd/types/types_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/types/types_windows.go | Apache-2.0 |
func InterfaceToStats(read time.Time, v interface{}) *Stats {
return &Stats{
Metrics: v,
Read: read,
}
} | InterfaceToStats returns a stats object from the platform-specific interface. | InterfaceToStats | go | balena-os/balena-engine | libcontainerd/types/types_linux.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/types/types_linux.go | Apache-2.0 |
func NewClient(ctx context.Context, cli *containerd.Client, stateDir, ns string, b libcontainerdtypes.Backend) (libcontainerdtypes.Client, error) {
c := &client{
stateDir: stateDir,
backend: b,
logger: logrus.WithField("module", "libcontainerd").WithField("module", "libcontainerd").WithField("namespace", ns),
containers: make(map[string]*container),
}
return c, nil
} | NewClient creates a new local executor for windows | NewClient | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Create(_ context.Context, id string, spec *specs.Spec, shim string, runtimeOptions interface{}, opts ...containerd.NewContainerOpts) error {
if ctr := c.getContainer(id); ctr != nil {
return errors.WithStack(errdefs.Conflict(errors.New("id already in use")))
}
var err error
if spec.Linux == nil {
err = c.createWindows(id, spec, runtimeOptions)
} else {
err = c.createLinux(id, spec, runtimeOptions)
}
if err == nil {
c.eventQ.Append(id, func() {
ei := libcontainerdtypes.EventInfo{
ContainerID: id,
}
c.logger.WithFields(logrus.Fields{
"container": id,
"event": libcontainerdtypes.EventCreate,
}).Info("sending event")
err := c.backend.ProcessEvent(id, libcontainerdtypes.EventCreate, ei)
if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{
"container": id,
"event": libcontainerdtypes.EventCreate,
}).Error("failed to process event")
}
})
}
return err
} | Create is the entrypoint to create a container from a spec.
Table below shows the fields required for HCS JSON calling parameters,
where if not populated, is omitted.
+-----------------+--------------------------------------------+---------------------------------------------------+
| | Isolation=Process | Isolation=Hyper-V |
+-----------------+--------------------------------------------+---------------------------------------------------+
| VolumePath | \\?\\Volume{GUIDa} | |
| LayerFolderPath | %root%\windowsfilter\containerID | |
| Layers[] | ID=GUIDb;Path=%root%\windowsfilter\layerID | ID=GUIDb;Path=%root%\windowsfilter\layerID |
| HvRuntime | | ImagePath=%root%\BaseLayerID\UtilityVM |
+-----------------+--------------------------------------------+---------------------------------------------------+
Isolation=Process example:
{
"SystemType": "Container",
"Name": "5e0055c814a6005b8e57ac59f9a522066e0af12b48b3c26a9416e23907698776",
"Owner": "docker",
"VolumePath": "\\\\\\\\?\\\\Volume{66d1ef4c-7a00-11e6-8948-00155ddbef9d}",
"IgnoreFlushesDuringBoot": true,
"LayerFolderPath": "C:\\\\control\\\\windowsfilter\\\\5e0055c814a6005b8e57ac59f9a522066e0af12b48b3c26a9416e23907698776",
"Layers": [{
"ID": "18955d65-d45a-557b-bf1c-49d6dfefc526",
"Path": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c"
}],
"HostName": "5e0055c814a6",
"MappedDirectories": [],
"HvPartition": false,
"EndpointList": ["eef2649d-bb17-4d53-9937-295a8efe6f2c"],
}
Isolation=Hyper-V example:
{
"SystemType": "Container",
"Name": "475c2c58933b72687a88a441e7e0ca4bd72d76413c5f9d5031fee83b98f6045d",
"Owner": "docker",
"IgnoreFlushesDuringBoot": true,
"Layers": [{
"ID": "18955d65-d45a-557b-bf1c-49d6dfefc526",
"Path": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c"
}],
"HostName": "475c2c58933b",
"MappedDirectories": [],
"HvPartition": true,
"EndpointList": ["e1bb1e61-d56f-405e-b75d-fd520cefa0cb"],
"DNSSearchList": "a.com,b.com,c.com",
"HvRuntime": {
"ImagePath": "C:\\\\control\\\\windowsfilter\\\\65bf96e5760a09edf1790cb229e2dfb2dbd0fcdc0bf7451bae099106bfbfea0c\\\\UtilityVM"
},
} | Create | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func setCommandLineAndArgs(isWindows bool, process *specs.Process, createProcessParms *hcsshim.ProcessConfig) {
if isWindows {
if process.CommandLine != "" {
createProcessParms.CommandLine = process.CommandLine
} else {
createProcessParms.CommandLine = system.EscapeArgs(process.Args)
}
} else {
createProcessParms.CommandArgs = process.Args
}
} | setCommandLineAndArgs configures the HCS ProcessConfig based on an OCI process spec | setCommandLineAndArgs | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Exec(ctx context.Context, containerID, processID string, spec *specs.Process, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (int, error) {
ctr := c.getContainer(containerID)
switch {
case ctr == nil:
return -1, errors.WithStack(errdefs.NotFound(errors.New("no such container")))
case ctr.hcsContainer == nil:
return -1, errors.WithStack(errdefs.InvalidParameter(errors.New("container is not running")))
case ctr.execs != nil && ctr.execs[processID] != nil:
return -1, errors.WithStack(errdefs.Conflict(errors.New("id already in use")))
}
logger := c.logger.WithFields(logrus.Fields{
"container": containerID,
"exec": processID,
})
// Note we always tell HCS to
// create stdout as it's required regardless of '-i' or '-t' options, so that
// docker can always grab the output through logs. We also tell HCS to always
// create stdin, even if it's not used - it will be closed shortly. Stderr
// is only created if it we're not -t.
createProcessParms := &hcsshim.ProcessConfig{
CreateStdInPipe: true,
CreateStdOutPipe: true,
CreateStdErrPipe: !spec.Terminal,
}
if spec.Terminal {
createProcessParms.EmulateConsole = true
if spec.ConsoleSize != nil {
createProcessParms.ConsoleSize[0] = uint(spec.ConsoleSize.Height)
createProcessParms.ConsoleSize[1] = uint(spec.ConsoleSize.Width)
}
}
// Take working directory from the process to add if it is defined,
// otherwise take from the first process.
if spec.Cwd != "" {
createProcessParms.WorkingDirectory = spec.Cwd
} else {
createProcessParms.WorkingDirectory = ctr.ociSpec.Process.Cwd
}
// Configure the environment for the process
createProcessParms.Environment = setupEnvironmentVariables(spec.Env)
// Configure the CommandLine/CommandArgs
setCommandLineAndArgs(ctr.isWindows, spec, createProcessParms)
logger.Debugf("exec commandLine: %s", createProcessParms.CommandLine)
createProcessParms.User = spec.User.Username
// Start the command running in the container.
newProcess, err := ctr.hcsContainer.CreateProcess(createProcessParms)
if err != nil {
logger.WithError(err).Errorf("exec's CreateProcess() failed")
return -1, err
}
pid := newProcess.Pid()
defer func() {
if err != nil {
if err := newProcess.Kill(); err != nil {
logger.WithError(err).Error("failed to kill process")
}
go func() {
if err := newProcess.Wait(); err != nil {
logger.WithError(err).Error("failed to wait for process")
}
if err := newProcess.Close(); err != nil {
logger.WithError(err).Error("failed to clean process resources")
}
}()
}
}()
dio, err := newIOFromProcess(newProcess, spec.Terminal)
if err != nil {
logger.WithError(err).Error("failed to get stdio pipes")
return -1, err
}
// Tell the engine to attach streams back to the client
_, err = attachStdio(dio)
if err != nil {
return -1, err
}
p := &process{
id: processID,
pid: pid,
hcsProcess: newProcess,
}
// Add the process to the container's list of processes
ctr.Lock()
ctr.execs[processID] = p
ctr.Unlock()
// Spin up a go routine waiting for exit to handle cleanup
go c.reapProcess(ctr, p)
c.eventQ.Append(ctr.id, func() {
ei := libcontainerdtypes.EventInfo{
ContainerID: ctr.id,
ProcessID: p.id,
Pid: uint32(p.pid),
}
c.logger.WithFields(logrus.Fields{
"container": ctr.id,
"event": libcontainerdtypes.EventExecAdded,
"event-info": ei,
}).Info("sending event")
err := c.backend.ProcessEvent(ctr.id, libcontainerdtypes.EventExecAdded, ei)
if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{
"container": ctr.id,
"event": libcontainerdtypes.EventExecAdded,
"event-info": ei,
}).Error("failed to process event")
}
err = c.backend.ProcessEvent(ctr.id, libcontainerdtypes.EventExecStarted, ei)
if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{
"container": ctr.id,
"event": libcontainerdtypes.EventExecStarted,
"event-info": ei,
}).Error("failed to process event")
}
})
return pid, nil
} | Exec adds a process in an running container | Exec | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) SignalProcess(_ context.Context, containerID, processID string, signal int) error {
ctr, p, err := c.getProcess(containerID, processID)
if err != nil {
return err
}
logger := c.logger.WithFields(logrus.Fields{
"container": containerID,
"process": processID,
"pid": p.pid,
"signal": signal,
})
logger.Debug("Signal()")
if processID == libcontainerdtypes.InitProcessName {
if syscall.Signal(signal) == syscall.SIGKILL {
// Terminate the compute system
ctr.Lock()
ctr.terminateInvoked = true
if err := ctr.hcsContainer.Terminate(); err != nil {
if !hcsshim.IsPending(err) {
logger.WithError(err).Error("failed to terminate hccshim container")
}
}
ctr.Unlock()
} else {
// Shut down the container
if err := ctr.hcsContainer.Shutdown(); err != nil {
if !hcsshim.IsPending(err) && !hcsshim.IsAlreadyStopped(err) {
// ignore errors
logger.WithError(err).Error("failed to shutdown hccshim container")
}
}
}
} else {
return p.hcsProcess.Kill()
}
return nil
} | Signal handles `docker stop` on Windows. While Linux has support for
the full range of signals, signals aren't really implemented on Windows.
We fake supporting regular stop and -9 to force kill. | SignalProcess | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) ResizeTerminal(_ context.Context, containerID, processID string, width, height int) error {
_, p, err := c.getProcess(containerID, processID)
if err != nil {
return err
}
c.logger.WithFields(logrus.Fields{
"container": containerID,
"process": processID,
"height": height,
"width": width,
"pid": p.pid,
}).Debug("resizing")
return p.hcsProcess.ResizeConsole(uint16(width), uint16(height))
} | Resize handles a CLI event to resize an interactive docker run or docker
exec window. | ResizeTerminal | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Pause(_ context.Context, containerID string) error {
ctr, _, err := c.getProcess(containerID, libcontainerdtypes.InitProcessName)
if err != nil {
return err
}
if ctr.ociSpec.Windows.HyperV == nil {
return errors.New("cannot pause Windows Server Containers")
}
ctr.Lock()
defer ctr.Unlock()
if err = ctr.hcsContainer.Pause(); err != nil {
return err
}
ctr.status = containerd.Paused
c.eventQ.Append(containerID, func() {
err := c.backend.ProcessEvent(containerID, libcontainerdtypes.EventPaused, libcontainerdtypes.EventInfo{
ContainerID: containerID,
ProcessID: libcontainerdtypes.InitProcessName,
})
c.logger.WithFields(logrus.Fields{
"container": ctr.id,
"event": libcontainerdtypes.EventPaused,
}).Info("sending event")
if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{
"container": containerID,
"event": libcontainerdtypes.EventPaused,
}).Error("failed to process event")
}
})
return nil
} | Pause handles pause requests for containers | Pause | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Resume(_ context.Context, containerID string) error {
ctr, _, err := c.getProcess(containerID, libcontainerdtypes.InitProcessName)
if err != nil {
return err
}
if ctr.ociSpec.Windows.HyperV == nil {
return errors.New("cannot resume Windows Server Containers")
}
ctr.Lock()
defer ctr.Unlock()
if err = ctr.hcsContainer.Resume(); err != nil {
return err
}
ctr.status = containerd.Running
c.eventQ.Append(containerID, func() {
err := c.backend.ProcessEvent(containerID, libcontainerdtypes.EventResumed, libcontainerdtypes.EventInfo{
ContainerID: containerID,
ProcessID: libcontainerdtypes.InitProcessName,
})
c.logger.WithFields(logrus.Fields{
"container": ctr.id,
"event": libcontainerdtypes.EventResumed,
}).Info("sending event")
if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{
"container": containerID,
"event": libcontainerdtypes.EventResumed,
}).Error("failed to process event")
}
})
return nil
} | Resume handles resume requests for containers | Resume | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Stats(_ context.Context, containerID string) (*libcontainerdtypes.Stats, error) {
ctr, _, err := c.getProcess(containerID, libcontainerdtypes.InitProcessName)
if err != nil {
return nil, err
}
readAt := time.Now()
s, err := ctr.hcsContainer.Statistics()
if err != nil {
return nil, err
}
return &libcontainerdtypes.Stats{
Read: readAt,
HCSStats: &s,
}, nil
} | Stats handles stats requests for containers | Stats | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Restore(ctx context.Context, id string, attachStdio libcontainerdtypes.StdioCallback) (bool, int, libcontainerdtypes.Process, error) {
c.logger.WithField("container", id).Debug("restore()")
// TODO Windows: On RS1, a re-attach isn't possible.
// However, there is a scenario in which there is an issue.
// Consider a background container. The daemon dies unexpectedly.
// HCS will still have the compute service alive and running.
// For consistence, we call in to shoot it regardless if HCS knows about it
// We explicitly just log a warning if the terminate fails.
// Then we tell the backend the container exited.
if hc, err := hcsshim.OpenContainer(id); err == nil {
const terminateTimeout = time.Minute * 2
err := hc.Terminate()
if hcsshim.IsPending(err) {
err = hc.WaitTimeout(terminateTimeout)
} else if hcsshim.IsAlreadyStopped(err) {
err = nil
}
if err != nil {
c.logger.WithField("container", id).WithError(err).Debug("terminate failed on restore")
return false, -1, nil, err
}
}
return false, -1, &restoredProcess{
c: c,
id: id,
}, nil
} | Restore is the handler for restoring a container | Restore | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) ListPids(_ context.Context, _ string) ([]uint32, error) {
return nil, errors.New("not implemented on Windows")
} | GetPidsForContainer returns a list of process IDs running in a container.
Not used on Windows. | ListPids | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) Summary(_ context.Context, containerID string) ([]libcontainerdtypes.Summary, error) {
ctr, _, err := c.getProcess(containerID, libcontainerdtypes.InitProcessName)
if err != nil {
return nil, err
}
p, err := ctr.hcsContainer.ProcessList()
if err != nil {
return nil, err
}
pl := make([]libcontainerdtypes.Summary, len(p))
for i := range p {
pl[i] = libcontainerdtypes.Summary{
ImageName: p[i].ImageName,
CreatedAt: p[i].CreateTimestamp,
KernelTime_100Ns: p[i].KernelTime100ns,
MemoryCommitBytes: p[i].MemoryCommitBytes,
MemoryWorkingSetPrivateBytes: p[i].MemoryWorkingSetPrivateBytes,
MemoryWorkingSetSharedBytes: p[i].MemoryWorkingSetSharedBytes,
ProcessID: p[i].ProcessId,
UserTime_100Ns: p[i].UserTime100ns,
ExecID: "",
}
}
return pl, nil
} | Summary returns a summary of the processes running in a container.
This is present in Windows to support docker top. In linux, the
engine shells out to ps to get process information. On Windows, as
the containers could be Hyper-V containers, they would not be
visible on the container host. However, libcontainerd does have
that information. | Summary | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) shutdownContainer(ctr *container) error {
var err error
const waitTimeout = time.Minute * 5
if !ctr.terminateInvoked {
err = ctr.hcsContainer.Shutdown()
}
if hcsshim.IsPending(err) || ctr.terminateInvoked {
err = ctr.hcsContainer.WaitTimeout(waitTimeout)
} else if hcsshim.IsAlreadyStopped(err) {
err = nil
}
if err != nil {
c.logger.WithError(err).WithField("container", ctr.id).
Debug("failed to shutdown container, terminating it")
terminateErr := c.terminateContainer(ctr)
if terminateErr != nil {
c.logger.WithError(terminateErr).WithField("container", ctr.id).
Error("failed to shutdown container, and subsequent terminate also failed")
return fmt.Errorf("%s: subsequent terminate failed %s", err, terminateErr)
}
return err
}
return nil
} | ctr mutex must be held when calling this function. | shutdownContainer | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) terminateContainer(ctr *container) error {
const terminateTimeout = time.Minute * 5
ctr.terminateInvoked = true
err := ctr.hcsContainer.Terminate()
if hcsshim.IsPending(err) {
err = ctr.hcsContainer.WaitTimeout(terminateTimeout)
} else if hcsshim.IsAlreadyStopped(err) {
err = nil
}
if err != nil {
c.logger.WithError(err).WithField("container", ctr.id).
Debug("failed to terminate container")
return err
}
return nil
} | ctr mutex must be held when calling this function. | terminateContainer | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func (c *client) reapContainer(ctr *container, p *process, exitCode int, exitedAt time.Time, eventErr error, logger *logrus.Entry) (int, error) {
// Update container status
ctr.Lock()
ctr.status = containerd.Stopped
ctr.exitedAt = exitedAt
ctr.exitCode = uint32(exitCode)
close(ctr.waitCh)
if err := c.shutdownContainer(ctr); err != nil {
exitCode = -1
logger.WithError(err).Warn("failed to shutdown container")
thisErr := errors.Wrap(err, "failed to shutdown container")
if eventErr != nil {
eventErr = errors.Wrap(eventErr, thisErr.Error())
} else {
eventErr = thisErr
}
} else {
logger.Debug("completed container shutdown")
}
ctr.Unlock()
if err := ctr.hcsContainer.Close(); err != nil {
exitCode = -1
logger.WithError(err).Error("failed to clean hcs container resources")
thisErr := errors.Wrap(err, "failed to terminate container")
if eventErr != nil {
eventErr = errors.Wrap(eventErr, thisErr.Error())
} else {
eventErr = thisErr
}
}
return exitCode, eventErr
} | reapContainer shuts down the container and releases associated resources. It returns
the error to be logged in the eventInfo sent back to the monitor. | reapContainer | go | balena-os/balena-engine | libcontainerd/local/local_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/local_windows.go | Apache-2.0 |
func setupEnvironmentVariables(a []string) map[string]string {
r := make(map[string]string)
for _, s := range a {
arr := strings.SplitN(s, "=", 2)
if len(arr) == 2 {
r[arr[0]] = arr[1]
}
}
return r
} | setupEnvironmentVariables converts a string array of environment variables
into a map as required by the HCS. Source array is in format [v1=k1] [v2=k2] etc. | setupEnvironmentVariables | go | balena-os/balena-engine | libcontainerd/local/utils_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/utils_windows.go | Apache-2.0 |
func (s *LCOWOption) Apply(interface{}) error {
return nil
} | Apply for the LCOW option is a no-op. | Apply | go | balena-os/balena-engine | libcontainerd/local/utils_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/utils_windows.go | Apache-2.0 |
func (c *container) debugGCS() {
if c == nil || c.isWindows || c.hcsContainer == nil {
return
}
cfg := opengcs.Config{
Uvm: c.hcsContainer,
UvmTimeoutSeconds: 600,
}
cfg.DebugGCS()
} | debugGCS is a dirty hack for debugging for Linux Utility VMs. It simply
runs a bunch of commands inside the UVM, but seriously aides in advanced debugging. | debugGCS | go | balena-os/balena-engine | libcontainerd/local/utils_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/local/utils_windows.go | Apache-2.0 |
func (q *Queue) Append(id string, f func()) {
q.Lock()
defer q.Unlock()
if q.fns == nil {
q.fns = make(map[string]chan struct{})
}
done := make(chan struct{})
fn, ok := q.fns[id]
q.fns[id] = done
go func() {
if ok {
<-fn
}
f()
close(done)
q.Lock()
if q.fns[id] == done {
delete(q.fns, id)
}
q.Unlock()
}()
} | Append adds an item to a queue. | Append | go | balena-os/balena-engine | libcontainerd/queue/queue.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/queue/queue.go | Apache-2.0 |
func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
p := &stdioPipes{}
if fifos.Stdin != "" {
c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("listen")
l, err := winio.ListenPipe(fifos.Stdin, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to create stdin pipe %s", fifos.Stdin)
}
dc := &delayedConnection{
l: l,
}
dc.wg.Add(1)
defer func() {
if err != nil {
dc.Close()
}
}()
p.stdin = dc
go func() {
c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("accept")
conn, err := l.Accept()
if err != nil {
dc.Close()
if err != winio.ErrPipeListenerClosed {
c.logger.WithError(err).Errorf("failed to accept stdin connection on %s", fifos.Stdin)
}
return
}
c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("connected")
dc.con = conn
dc.unblockConnectionWaiters()
}()
}
if fifos.Stdout != "" {
c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("listen")
l, err := winio.ListenPipe(fifos.Stdout, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to create stdout pipe %s", fifos.Stdout)
}
dc := &delayedConnection{
l: l,
}
dc.wg.Add(1)
defer func() {
if err != nil {
dc.Close()
}
}()
p.stdout = dc
go func() {
c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("accept")
conn, err := l.Accept()
if err != nil {
dc.Close()
if err != winio.ErrPipeListenerClosed {
c.logger.WithError(err).Errorf("failed to accept stdout connection on %s", fifos.Stdout)
}
return
}
c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("connected")
dc.con = conn
dc.unblockConnectionWaiters()
}()
}
if fifos.Stderr != "" {
c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("listen")
l, err := winio.ListenPipe(fifos.Stderr, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to create stderr pipe %s", fifos.Stderr)
}
dc := &delayedConnection{
l: l,
}
dc.wg.Add(1)
defer func() {
if err != nil {
dc.Close()
}
}()
p.stderr = dc
go func() {
c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("accept")
conn, err := l.Accept()
if err != nil {
dc.Close()
if err != winio.ErrPipeListenerClosed {
c.logger.WithError(err).Errorf("failed to accept stderr connection on %s", fifos.Stderr)
}
return
}
c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("connected")
dc.con = conn
dc.unblockConnectionWaiters()
}()
}
return p, nil
} | newStdioPipes creates actual fifos for stdio. | newStdioPipes | go | balena-os/balena-engine | libcontainerd/remote/client_io_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client_io_windows.go | Apache-2.0 |
func WithBundle(bundleDir string, ociSpec *specs.Spec) containerd.NewContainerOpts {
return func(ctx context.Context, client *containerd.Client, c *containers.Container) error {
// TODO: (containerd) Determine if we need to use system.MkdirAllWithACL here
if c.Labels == nil {
c.Labels = make(map[string]string)
}
c.Labels[DockerContainerBundlePath] = bundleDir
return os.MkdirAll(bundleDir, 0755)
}
} | WithBundle creates the bundle for the container | WithBundle | go | balena-os/balena-engine | libcontainerd/remote/client_windows.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client_windows.go | Apache-2.0 |
func WithBundle(bundleDir string, ociSpec *specs.Spec) containerd.NewContainerOpts {
return func(ctx context.Context, client *containerd.Client, c *containers.Container) error {
if c.Labels == nil {
c.Labels = make(map[string]string)
}
uid, gid := getSpecUser(ociSpec)
if uid == 0 && gid == 0 {
c.Labels[DockerContainerBundlePath] = bundleDir
return idtools.MkdirAllAndChownNew(bundleDir, 0755, idtools.Identity{UID: 0, GID: 0})
}
p := string(filepath.Separator)
components := strings.Split(bundleDir, string(filepath.Separator))
for _, d := range components[1:] {
p = filepath.Join(p, d)
fi, err := os.Stat(p)
if err != nil && !os.IsNotExist(err) {
return err
}
if os.IsNotExist(err) || fi.Mode()&1 == 0 {
p = fmt.Sprintf("%s.%d.%d", p, uid, gid)
if err := idtools.MkdirAndChown(p, 0700, idtools.Identity{UID: uid, GID: gid}); err != nil && !os.IsExist(err) {
return err
}
}
}
if c.Labels == nil {
c.Labels = make(map[string]string)
}
c.Labels[DockerContainerBundlePath] = p
return nil
}
} | WithBundle creates the bundle for the container | WithBundle | go | balena-os/balena-engine | libcontainerd/remote/client_linux.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client_linux.go | Apache-2.0 |
func NewClient(ctx context.Context, cli *containerd.Client, stateDir, ns string, b libcontainerdtypes.Backend) (libcontainerdtypes.Client, error) {
c := &client{
client: cli,
stateDir: stateDir,
logger: logrus.WithField("module", "libcontainerd").WithField("namespace", ns),
ns: ns,
backend: b,
oom: make(map[string]bool),
v2runcoptions: make(map[string]v2runcoptions.Options),
}
go c.processEventStream(ctx, ns)
return c, nil
} | NewClient creates a new libcontainerd client from a containerd client | NewClient | go | balena-os/balena-engine | libcontainerd/remote/client.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client.go | Apache-2.0 |
func (c *client) Restore(ctx context.Context, id string, attachStdio libcontainerdtypes.StdioCallback) (alive bool, pid int, p libcontainerdtypes.Process, err error) {
var dio *cio.DirectIO
defer func() {
if err != nil && dio != nil {
dio.Cancel()
dio.Close()
}
err = wrapError(err)
}()
ctr, err := c.client.LoadContainer(ctx, id)
if err != nil {
return false, -1, nil, errors.WithStack(wrapError(err))
}
attachIO := func(fifos *cio.FIFOSet) (cio.IO, error) {
// dio must be assigned to the previously defined dio for the defer above
// to handle cleanup
dio, err = c.newDirectIO(ctx, fifos)
if err != nil {
return nil, err
}
return attachStdio(dio)
}
t, err := ctr.Task(ctx, attachIO)
if err != nil && !containerderrors.IsNotFound(err) {
return false, -1, nil, errors.Wrap(wrapError(err), "error getting containerd task for container")
}
if t != nil {
s, err := t.Status(ctx)
if err != nil {
return false, -1, nil, errors.Wrap(wrapError(err), "error getting task status")
}
alive = s.Status != containerd.Stopped
pid = int(t.Pid())
}
c.logger.WithFields(logrus.Fields{
"container": id,
"alive": alive,
"pid": pid,
}).Debug("restored container")
return alive, pid, &restoredProcess{
p: t,
}, nil
} | Restore loads the containerd container.
It should not be called concurrently with any other operation for the given ID. | Restore | go | balena-os/balena-engine | libcontainerd/remote/client.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client.go | Apache-2.0 |
func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (int, error) {
ctr, err := c.getContainer(ctx, id)
if err != nil {
return -1, err
}
var (
cp *types.Descriptor
t containerd.Task
rio cio.IO
stdinCloseSync = make(chan struct{})
)
if checkpointDir != "" {
// write checkpoint to the content store
tar := archive.Diff(ctx, "", checkpointDir)
cp, err = c.writeContent(ctx, images.MediaTypeContainerd1Checkpoint, checkpointDir, tar)
// remove the checkpoint when we're done
defer func() {
if cp != nil {
err := c.client.ContentStore().Delete(context.Background(), cp.Digest)
if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{
"ref": checkpointDir,
"digest": cp.Digest,
}).Warnf("failed to delete temporary checkpoint entry")
}
}
}()
if err := tar.Close(); err != nil {
return -1, errors.Wrap(err, "failed to close checkpoint tar stream")
}
if err != nil {
return -1, errors.Wrapf(err, "failed to upload checkpoint to containerd")
}
}
spec, err := ctr.Spec(ctx)
if err != nil {
return -1, errors.Wrap(err, "failed to retrieve spec")
}
labels, err := ctr.Labels(ctx)
if err != nil {
return -1, errors.Wrap(err, "failed to retrieve labels")
}
bundle := labels[DockerContainerBundlePath]
uid, gid := getSpecUser(spec)
taskOpts := []containerd.NewTaskOpts{
func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
info.Checkpoint = cp
return nil
},
}
if runtime.GOOS != "windows" {
taskOpts = append(taskOpts, func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
c.v2runcoptionsMu.Lock()
opts, ok := c.v2runcoptions[id]
c.v2runcoptionsMu.Unlock()
if ok {
opts.IoUid = uint32(uid)
opts.IoGid = uint32(gid)
info.Options = &opts
} else {
info.Options = &runctypes.CreateOptions{
IoUid: uint32(uid),
IoGid: uint32(gid),
NoPivotRoot: os.Getenv("DOCKER_RAMDISK") != "",
}
}
return nil
})
} else {
taskOpts = append(taskOpts, withLogLevel(c.logger.Level))
}
t, err = ctr.NewTask(ctx,
func(id string) (cio.IO, error) {
fifos := newFIFOSet(bundle, libcontainerdtypes.InitProcessName, withStdin, spec.Process.Terminal)
rio, err = c.createIO(fifos, id, libcontainerdtypes.InitProcessName, stdinCloseSync, attachStdio)
return rio, err
},
taskOpts...,
)
if err != nil {
close(stdinCloseSync)
if rio != nil {
rio.Cancel()
rio.Close()
}
return -1, wrapError(err)
}
// Signal c.createIO that it can call CloseIO
close(stdinCloseSync)
if err := t.Start(ctx); err != nil {
if _, err := t.Delete(ctx); err != nil {
c.logger.WithError(err).WithField("container", id).
Error("failed to delete task after fail start")
}
return -1, wrapError(err)
}
return int(t.Pid()), nil
} | Start create and start a task for the specified containerd id | Start | go | balena-os/balena-engine | libcontainerd/remote/client.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client.go | Apache-2.0 |
func (c *client) Exec(ctx context.Context, containerID, processID string, spec *specs.Process, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (int, error) {
ctr, err := c.getContainer(ctx, containerID)
if err != nil {
return -1, err
}
t, err := ctr.Task(ctx, nil)
if err != nil {
if containerderrors.IsNotFound(err) {
return -1, errors.WithStack(errdefs.InvalidParameter(errors.New("container is not running")))
}
return -1, wrapError(err)
}
var (
p containerd.Process
rio cio.IO
stdinCloseSync = make(chan struct{})
)
labels, err := ctr.Labels(ctx)
if err != nil {
return -1, wrapError(err)
}
fifos := newFIFOSet(labels[DockerContainerBundlePath], processID, withStdin, spec.Terminal)
defer func() {
if err != nil {
if rio != nil {
rio.Cancel()
rio.Close()
}
}
}()
p, err = t.Exec(ctx, processID, spec, func(id string) (cio.IO, error) {
rio, err = c.createIO(fifos, containerID, processID, stdinCloseSync, attachStdio)
return rio, err
})
if err != nil {
close(stdinCloseSync)
if containerderrors.IsAlreadyExists(err) {
return -1, errors.WithStack(errdefs.Conflict(errors.New("id already in use")))
}
return -1, wrapError(err)
}
// Signal c.createIO that it can call CloseIO
//
// the stdin of exec process will be created after p.Start in containerd
defer close(stdinCloseSync)
if err = p.Start(ctx); err != nil {
// use new context for cleanup because old one may be cancelled by user, but leave a timeout to make sure
// we are not waiting forever if containerd is unresponsive or to work around fifo cancelling issues in
// older containerd-shim
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
p.Delete(ctx)
return -1, wrapError(err)
}
return int(p.Pid()), nil
} | Exec creates exec process.
The containerd client calls Exec to register the exec config in the shim side.
When the client calls Start, the shim will create stdin fifo if needs. But
for the container main process, the stdin fifo will be created in Create not
the Start call. stdinCloseSync channel should be closed after Start exec
process. | Exec | go | balena-os/balena-engine | libcontainerd/remote/client.go | https://github.com/balena-os/balena-engine/blob/master/libcontainerd/remote/client.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.